I need to deserialize a JSON array to a HashMap with jackson

Viewed 518

I have a json file which I need to deserialize into a HashMap.

I need a HashMap of type {name, HashMap<valuename, value>}

Example: {aaa={value1=111, value2=222, value3=333}, bbb={value1=444, value2=555, value3=666}}

Unfortunately, I'm new to json and jackson.

Thank you in advance.

Here is my json

[
    {
        "name": "aaa",
        "values" : {
            "value1" : 111,
            "value2" : 222,
            "value3" : 333
        }
    },
    {
        "name": "bbb",
        "values" : {
            "value1" : 444,
            "value2" : 555,
            "value3" : 666
        }
    }
]

and my classes:

public class Elements {
    
    @JsonProperty("name")
    String name;
    @JsonProperty("values")
    Values values;
    
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Values getValues() {
        return this.values;
    }

    public void setValues(Values values) {
        this.values = values;
    }
}
public class Values {
    @JsonProperty("value1")
    int value1;
    @JsonProperty("value2")
    int value2;
    @JsonProperty("value3")
    int value3;

    public int getValue1() {
        return this.value1;
    }

    public void setValue1(int value1) {
        this.value1 = value1;
    }

    public int getValue2() {
        return this.value2;
    }

    public void setValue2(int value2) {
        this.value2 = value2;
    }

    public int getValue3() {
        return this.value3;
    }

    public void setValue3(int value3) {
        this.value3 = value3;
    }
}
2 Answers

Just read it as a List of Map instances and collect it to a new Map after deserialisation process:

List<Map<String, Object>> listOfMaps = mapper.readValue(json, new TypeReference<List<Map<String, Object>>>() {});
Map<String, Object> desiredMap = listOfMaps.stream().collect(HashMap::new,
        (result, map) -> result.put(map.get("name").toString(), map.get("values")),
        (existing, replacement) -> { });

I've upvoted @Michal's answer as it is really cool and delivers what you asked for:

I need a HashMap of type {name, HashMap<valuename, value>}

I don't understand why you have defined the Elements and Values classes if all you want is to store the data within a HashMap of HashMaps.

Out of curiosity, I tested Jackson with your classes and it works just fine:

// Deserialize as a list
List<Elements> listElements = objectMapper.readValue(JSON, new TypeReference<List<Elements>>(){});
// print elements
listElements.forEach(System.out::println);
Related