Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize into Map<String, String> with Jackson

Tags:

java

json

jackson

I have the following JSON:

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

Note that the contract of this response guarantees that keys are unique.

I would like to deseralize this into the following class:

public class Response {

  public Map<String, String> parameters;

}

How can i do this using the Jackson library?

like image 716
WonderCsabo Avatar asked Jan 02 '18 11:01

WonderCsabo


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;
    }   
}
like image 75
Maurice Perry Avatar answered Sep 22 '22 02:09

Maurice Perry


You will need a custom deserializer for this.

like image 20
Fortega Avatar answered Sep 22 '22 02:09

Fortega