data is an object with two properties.
JSON.parse() fails because it isn't a string of JSON.
data[0] doesn't return anything because it has no such property.
You want data.key1.
Parsing JSON in javascript coming from Java Jackson JSON - Stack Overflow
java - How to parse a JSON string into JsonNode in Jackson? - Stack Overflow
JSON string to Java object with Jackson - Stack Overflow
java - jackson parsing javascript function - Stack Overflow
Videos
A slight variation on Richards answer but readTree can take a string so you can simplify it to:
ObjectMapper mapper = new ObjectMapper();
JsonNode actualObj = mapper.readTree("{\"k1\":\"v1\"}");
You need to use an ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getJsonFactory(); // since 2.1 use mapper.getFactory() instead
JsonParser jp = factory.createJsonParser("{\"k1\":\"v1\"}");
JsonNode actualObj = mapper.readTree(jp);
Further documentation about creating parsers can be found here.
Try this,
You can't create a new string like your doing.
String string = "{\"id\":100,\"firstName\":\"Adam\"}";
Student student = mapper.readValue(string, Student.class);
And instead of handling errors in every mapper.readValue(json, Class) you can write a helper class which has another Generic method.
and use
String jsonString = "{\"id\":100,\"firstName\":\"Adam\"}";
Student student = JSONUtils.convertToObject(jsonString, Student.class);
I'm returning null and fancying printing trace & checking null later on. You can handle error cases on your own way.
public class JSONUtils {
public static String convertToJSON(Object object) {
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json;
try {
json = ow.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
return convertToJSON(e);
}
return json;
}
public static <T> T convertToObject(Class<T> clazz, String jsonString) {
try {
ObjectMapper mapper = new ObjectMapper();
return (T) mapper.readValue(jsonString, clazz);
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
}
JSON doesn't allow functions. It is meant for safe data-transfer though you could encode the function as a string like this:
{
"key1" : "value1",
"key2" : "value2",
"key3" : "function () { ... }"
}
...but upon re-encoding, it would be a string rather than a function unless you were to eval() it (though that could well be unsafe).
This is not valid JSON, and it is not supported by Jackson; nor is it likely to be supported in future. I would suggest making that a regular JSON String, and then re-parsing on Javascript side if and as necessary.