Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map JSON To List<Map<<String, Object>>

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.

like image 256
Pranay Kumar Avatar asked Jun 22 '17 11:06

Pranay Kumar


People also ask

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.

How do I string a JSON object?

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.

Is a map a JSON object?

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.


2 Answers

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>>>(){});
like image 192
Manos Nikolaidis Avatar answered Oct 11 '22 09:10

Manos Nikolaidis


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);
like image 35
alexey28 Avatar answered Oct 11 '22 07:10

alexey28