Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a List of json object to hashmap using jackson

Is there a way to use inbuilt Jackson capabilities to convert a list of json object to HashMap using java

Explanation: Json structure that i need to parse

{
    list:[
        {
            keyId : 1,
            keyLabel : "Test 1",
            valueId: 34,
            valueLabel: "Test Lable"
        },
        {
            keyId : 2,
            keyLabel : "Test 2",
            valueId: 35,
            valueLabel: "Test Lable"
        },
        {
            keyId : 3,
            keyLabel : "Test 3",
            valueId: 36,
            valueLabel: "Test Lable"
        }
    ]
}

The object model I am expecting,

class Key{
    int keyId;
    String keyLable;

    hashCode(){
    return keyId.hashCode();
    }
}

class Value{
    int valueId;
    String valueLable;

    hashCode(){
    return valueId.hashCode();
    }
}

I need to convert the above json list to a map like this,

HashMap<Key,Value> map;
like image 584
Ysak Avatar asked Mar 04 '16 05:03

Ysak


People also ask

How do I convert JSON objects to Jackson?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.

How do you pass a JSON object into a Map?

In order to convert JSON data into Java Map, we take help of JACKSON library. We add the following dependency in the POM. xml file to work with JACKSON library. Let's implement the logic of converting JSON data into a map using ObjectMapper, File and TypeReference classes.

What is the use of Jackson ObjectMapper?

ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.


1 Answers

I would suggest to do it manually. You just have to write few lines. Something Like

    ObjectMapper jmap = new ObjectMapper();
    //Ignore value properties
    List<Key> keys = jmap.readValue("[{}, {}]", jmap.getTypeFactory().constructCollectionType(ArrayList.class, Key.class));
    //Ignore key properties
    List<Value> values = jmap.readValue("[{}, {}]", jmap.getTypeFactory().constructCollectionType(ArrayList.class, Value.class));

    Map<Key, Value> data = new HashMap<>();
    for (int i = 0; i < keys.size(); i++) {
        data.put(keys.get(i), values.get(i));
    }

Note: There is spell mismatch in your json and model (valueLabel != valueLable).

like image 114
M Faisal Hameed Avatar answered Oct 05 '22 19:10

M Faisal Hameed