Map an array of JSON objects to a java.util.Map and vice versa
Asked Answered
E

3

10

The question is how to map an array of JSON objects to a java.util.Map where each key would be some specified property of an object and the value is the object itself.

JSON:

{"items": [{"field1": 1, "field2": "Hello"}, {"field1": 2, "field2":"World"}]}

Java POJO:

public class Storage {
    private Map<Integer, Item> items;
}

public class Item {
    private Integer field1;
    private String field2;
}

So is there a some way to specify to ObjectMapper that it should use field1 property of each JSON object as key when deserializing array of items to the Map?

Egidio answered 25/11, 2015 at 10:45 Comment(0)
P
7

How to deserialize a JSON string

You can use Jackson to deserialize a JSON string:

For example if you have class Foo

public class Foo {

   private Bar[] items;

   // Constructor / Getters & Setters

} 

And that class has an array of class Bar

 public class Bar {

     private int field1;
     private String field2;


     // Constructor / Getters & Setters

 }

Where the field names match those in your JSON string then you can do the following to convert it:

String jsonString = "{\"items\": [{\"field1\": 1, \"field2\": \"Hello\"}, {\"field1\": 2, \"field2\":\"World\"}]}";

ObjectMapper mapper = new ObjectMapper();

Foo foo = mapper.readValue(jsonString, Foo.class);

If you are using Maven, the following dependency would be required in your pom.xml:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>${jackson.version}</version>
    </dependency>

Approaches to solve your problem:

Option 1 - Custom Deserializer

Write a custom JsonDeserializer to deserialize your JSON string into a Storage object with a field items of type Map<String,Item>

 public class CustomDeserializer extends JsonDeserializer<Storage> {

    @Override
    public Storage deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
            throws IOException {

        Map<Integer, Item> map = new HashMap<>();

        ObjectCodec oc = jsonParser.getCodec();
        JsonNode rootNode = oc.readTree(jsonParser);
        JsonNode items = rootNode.get("items");

        for (int i = 0; i < items.size(); i++) {

            JsonNode childNode = items.get(i);

            Item item = new Item(childNode.get("field1").asInt(), childNode.get("field2").asText());

            map.put(item.getField1(), item);
        }

        return new Storage(map);
    }
}

You would then annotate your Storage class with the following:

@JsonDeserialize(using = CustomDeserializer.class)

Your Storage class would look something like;

@JsonDeserialize(using = CustomDeserializer.class)
public class Storage {

   private Map<Integer, Item> items;

   public Storage(Map<Integer, Item> map) {
    this.items = map;
   }

   ...

}

Option 2 - Create Map post deserialization

Deserialize the JSON string into a Storage object with an array of Item as described at the beginning and then construct your Map<Integer, Item> after.

Hope this helps.

Platoon answered 25/11, 2015 at 11:6 Comment(1)
It doesn't solve my problem. I know, how to deserialize the JSON object in case the items is just an array or some Collection. Again: I want to deserialize items into Map with the mappings where key is the property of the object stored in value.Egidio
Y
1

You can create your own custom Serializers/Deserializers to achieve this. Jackson provides a neat way of doing this. Just annotate the Storage class with @JsonDeserialize(using = YourDeserializer.class) and have the logic to convert the json in YourDeserializer.

Yajairayajurveda answered 25/11, 2015 at 11:21 Comment(0)
E
0

The array of JSON objects is an array of Items, right? So why not simply deserialize the array into a Java array of Items and then build the Map from there?

Ezekielezell answered 25/11, 2015 at 13:10 Comment(1)
Because in my case there is underlying generic source (DAO) which has all the serialization/deserialization logic using ObjectMapper in the background. I don't want to change anything there. At this moment the solution with custom serializer/deserializer seems to be the only way to achieve what I want...Egidio

© 2022 - 2024 — McMap. All rights reserved.