Deserialize to Map <String, String> using Jackson

I have the following JSON:

{
  "parameters": [{
      "value": "somevalue",
      "key": "somekey"
    },
    {
      "value": "othervalue",
      "key": "otherkey"
    }
  ]
}

Please note that the contract of this answer guarantees the uniqueness of the keys.

I would like to do this in the following class:

public class Response {

  public Map<String, String> parameters;

}

How can I do this using the Jackson library?

+4
source share
2 answers

You need to register a deserializer:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Response.class, new ResponseDeserializer());
mapper.registerModule(module);

Response resp = mapper.readValue(myjson, Response.class);

Here is an example:

public class ResponseDeserializer extends StdDeserializer<Response> {
    public ResponseDeserializer() { 
        this(null); 
    } 

    public ResponseDeserializer(Class<?> vc) { 
        super(vc); 
    }

    @Override
    public Response deserialize(JsonParser jp, DeserializationContext dc)
            throws IOException, JsonProcessingException {
        Response resp = new Response();
        resp.parameters = new HashMap<>();
        JsonNode node = jp.getCodec().readTree(jp);
        ArrayNode parms = (ArrayNode)node.get("parameters");
        for (JsonNode parm: parms) {
            String key = parm.get("key").asText();
            String value = parm.get("value").asText();
            resp.parameters.put(key, value);
        }
        return resp;
    }   
}
+3
source

To do this, you will need a custom deserializer .

+2
source

Source: https://habr.com/ru/post/1691615/


All Articles