I have json objects in the following schema:
{
name: \"foo\",
timestamp: 1475840608763,
payload:
{
foo: \"bar\"
}
}
Here, th
JsonNodeYou could use JsonNode from the com.fasterxml.jackson.databind package:
public class Event {
public String name;
public long timestamp;
public JsonNode payload;
// Getters and setters
}
Then parse it using:
String json = "{\"name\":\"foo\",\"timestamp\":1475840608763,"
+ "\"payload\":{\"foo\":\"bar\"}}";
ObjectMapper mapper = new ObjectMapper();
Event event = mapper.readValue(json, Event.class);
JsonNode to a POJOConsider, for example, you want to map the JsonNode instance to the following class:
public class Payload {
private String foo;
// Getters and setters
}
It can be achieved with the following piece of code:
Payload payload = mapper.treeToValue(event.getPayload(), Payload.class);
MapDepending on your requirements, you could use a Map instead of JsonNode:
public class Event {
public String name;
public long timestamp;
public Map payload;
// Getters and setters
}
If you need to convert a Map to a POJO, use:
Payload payload = mapper.convertValue(event.getPayload(), Payload.class);
According to the Jackson documentation, the convertValue() method is functionally similar to first serializing given value into JSON, and then binding JSON data into value of given type, but should be more efficient since full serialization does not (need to) occur. However, same converters (serializers and deserializers) will be used as for data binding, meaning same object mapper configuration works.