Lolo
Lolo

Reputation: 4159

How do deserialize a json object with a Map as one of its properties

I have been using jackson to deserialize successfully json objects and arrays, but this time I just can't wrap my head around how to approach deserialization for the following object. How can I, with Jackson or any other json parsing library, deserialize:

 [
    {
        "name": "x",
        "elements": {
            "key1": {
                "name": "a",
                "type": "b"
            },
            "key2": {
                "name": "a",
                "type": "b"
            }
        }
    },
    {
        "name": "y",
        "elements": {
            "key3": {
                "name": "a",
                "type": "b"
            }
        }
    }
 ]

into a list, List<Test>, where Test is defined below?

public class Test {     
    public class Element {
        public String name;
        public String type;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getType() {
            return type;
        }
        public void setType(String type) {
            this.type = type;
        }
    }
    public String name;
    public Map<String, Element> elements;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Map<String, Element> getElements() {
        return elements;
    }
    public void setElements(Map<String, Element> elements) {
        this.elements = elements;
    }  
} 

Finally, my deserializing code:

  public List<Test> test(final InputStream inputStream) {
    List<Test> test = null;
    try {
      test = mapper.readValue(inputStream, new TypeReference<List<Test>>() { });
    }  catch (final IOException e) {
      log.error("Unable to deserialize json",e);
    }
    return test;
  }

If that is not possible, what object can I actually deserialize my json into? One thing I cannot know ahead of time is the name of the keys (key1, key2, key3 in the example).

Upvotes: 0

Views: 1733

Answers (1)

StaxMan
StaxMan

Reputation: 116512

It looks like this:

ObjectMapper mapper = new ObjectMapper();
List<Test> tests = mapper.readValue(jsonInput, new TypeReference<List<Test>>() { };

would do it. The only tricky part is that TypeReference, which is needed to pass generic type information. Other libs use similar approaches (GSON has TypeToken or such).

Upvotes: 2

Related Questions