Mapping a dynamic json object field in Jackson?

Click Upvote :

I have json objects in the following schema:

{
  name: "foo",
  timestamp: 1475840608763,
  payload:
  {
     foo: "bar"
  }
}

Here, the payload field contains an embedded json object, and the schema of this object is dynamic, and different each time.

The payload object is the raw output obtained from different API services, and different methods of different API services. It isn't possible to map it to all possible values.

Is it possible to have a java class such as the following:

public class Event
{
    public String name;
    public long timestamp;
    public JsonObject payload;
}

Or something along those lines, so I can receive the basic schema and process it, then send it to the relevant class which will convert payload to its appropriate expected class?

cassiomolin :

Using JsonNode

You 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);

Mapping JsonNode to a POJO

Consider, 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);

Considering a Map<String, Object>

Depending on your requirements, you could use a Map<String, Object> instead of JsonNode:

public class Event {

    public String name;
    public long timestamp;
    public Map<String, Object> payload;

    // Getters and setters
}

If you need to convert a Map<String, Object> 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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=448796&siteId=1