2

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") 
2
  • Haven't done any serious delving or testing, but, for one, I'd say Jackson might have a problem with your nested class Temp being a) private, and b) an inner class (non-static, hence bound to the instance of the containing MediaSlideShow). So I'd start with making Temp public static. Commented Feb 15, 2012 at 3:47
  • And do you specifically need a HashMap? If not, consider a Map<String, Temp> instead and let Jackson worry about what implementation to use. Commented Feb 15, 2012 at 3:49

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.