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;
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With