user1118019 user1118019 - 6 months ago 38
JSON Question

Mapping Json string to map or hashmap field in java

Say I have the following JSON string returned from server:

{
"response":{
"imageInstances":{
"one":{
"id":"1",
"url":"ONE"
},
"two":{
"id":"2",
"url":"TWO"
}
}
}
}


in codehaus Jackson
@JsonProperty
, how can I get a
HashMap
object out of it?

import org.codehaus.jackson.annotate.JsonAnySetter;
import org.codehaus.jackson.annotate.JsonProperty;

import java.util.HashMap;
import java.util.List;

public class MSShow {
@JsonProperty("imageInstances") private HashMap<String, Temp> images;//// HOW DO YOU CONVERT IT TO HASH MAP??????
@JsonAnySetter public void ignoredField(String key, Object value) { }

private class Temp {
@JsonProperty("id") private String id;
@JsonProperty("url") private String url;
@JsonAnySetter public void ignoredField(String key, Object value) { }
}
}


At the end of the day, I want the hash map generated based on the returned JSON string to be
(written in java pseudo)

should return me a Temp object with fields
id=1
and
url=ONE
if I call

images.get("one")


should return me a Temp object with fields
id=2
and
url=TWO
if I call

images.get("two")

Answer

That should work as is, with one small modification: you are using extra "response" entry. So typically you would either use a wrapper POJO like:

class Wrapper {
  public MSShow response;
}

to map structure properly. Or you can use UNWRAP_ROOT_VALUE Feature (from DeserializationConfig) to do this automatically, although name of the class needs to match if so.

Result will indeed be a HashMap if the field type is that (which it is). If it wasn't you could also use:

@JsonDeserialize(as=HashMap.class)

to force specific subtype to be used.