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?
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;
}
}
You will need a custom deserializer for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With