I have a JSON of the format
[{
"id" : "a01",
"name" : "random1",
"val" : "random2"
},
{
"id" : "a03",
"name" : "random3",
"val" : "random4"
}]
I need to map it to a List
holding various Map
objects. How do I achieve it?
Even if I am able to convert this JSON to a List
of String
of the form
{
"id" : "a01",
"name" : "random1",
"val" : "random2"
}
then I have a method to convert each individual String
to 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.
Stringify a JavaScript Objectstringify() to convert it into a string. const myJSON = JSON. stringify(obj); The result will be a string following the JSON notation.
A JSONObject is an unordered collection of name/value pairs whereas Map is an object that maps keys to values. A Map cannot contain duplicate keys and each key can map to at most one value.
You will need to pass a TypeReference
to readValue
with the desired result type:
ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object>> data = mapper.readValue(json, new TypeReference<List<Map<String, Object>>>(){});
Use gson with specified type to convert to list of maps:
Gson gson = new Gson();
Type resultType = new TypeToken<List<Map<String, Object>>>(){}.getType();
List<Map<String, Object>> result = gson.fromJson(json, resultType);
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