Mapping a dynamic json object field in Jackson?

后端 未结 2 1291
野的像风
野的像风 2020-12-03 07:58

I have json objects in the following schema:

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

Here, th

2条回答
  •  借酒劲吻你
    2020-12-03 08:22

    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

    Depending 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.

提交回复
热议问题