user1710727
user1710727

Reputation: 23

Java Array with multiple Json objects convertion to List Hashmap

Basically, I have api response as below:

{
  "body": [
    {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3",
      "key4": "value4"
    },
    {
      "key1": "value1",
      "key2": "value2",
      "key3": "value3",
      "key4": "value4"
    },
    ...
  ]
}

I want to convert it to a list of hash map for each object above. How can I do that?

Upvotes: 1

Views: 1155

Answers (2)

Evgeni Genchev
Evgeni Genchev

Reputation: 47

Just use GenSON. The function parseKeys(String json) returns HashMap. The link for the lib: https://github.com/EvgeniGenchev/GenSON-lib I made the library for this specific use case.

Upvotes: 0

Dui Samarasinghe
Dui Samarasinghe

Reputation: 247

You can refer below code to get an idea. In code first few lines I have created json as you give. But if you get this json response by RestTemplate you can simply get it as JSONObject. Then you can create a method to parse that JSONObject and return List of Map as in below code.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

public class JsonObject {

    public static void main(String[] args) {
        JSONObject mainObj = new JSONObject();
        JSONArray bodyArray = new JSONArray();

        JSONObject element1 = new JSONObject();
        element1.accumulate("key1", "value1");
        element1.accumulate("key2", "value2");
        element1.accumulate("key3", "value3");
        element1.accumulate("key4", "value4");

        JSONObject element2 = new JSONObject();
        element2.accumulate("key21", "value21");
        element2.accumulate("key22", "value22");
        element2.accumulate("key23", "value23");
        element2.accumulate("key24", "value24");

        bodyArray.put(element1);
        bodyArray.put(element2);
        //System.out.println(bodyArray);

        mainObj.put("body", bodyArray);

        System.out.println(mainObj);

        List<Map<String, String>> mapList = new ArrayList<Map<String,String>>();
        JSONArray gotArray = (JSONArray) mainObj.get("body");
        for(int i=0; i<gotArray.length(); i++) {
            JSONObject obj = gotArray.getJSONObject(i);

            Map<String, String> object = new HashMap<String,String>();

            for(String key : obj.keySet()) {
                object.put(key, obj.getString(key));
            }

            mapList.add(object);
        }

        System.out.println(mapList);

    }
}

Upvotes: 1

Related Questions