简体   繁体   English

Java 数组与多个 Json 对象转换为列表 Hashmap

[英]Java Array with multiple Json objects convertion to List Hashmap

Basically, I have api response as below:基本上,我的 api 响应如下:

{
  "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.我想将其转换为上面每个 object 的 hash map 的列表。 How can I do that?我怎样才能做到这一点?

You can refer below code to get an idea.您可以参考下面的代码来了解一下。 In code first few lines I have created json as you give.在代码的前几行中,我按照您的要求创建了 json。 But if you get this json response by RestTemplate you can simply get it as JSONObject.但是,如果您通过 RestTemplate 获得此 json 响应,您可以简单地将其作为 JSONObject 获取。 Then you can create a method to parse that JSONObject and return List of Map as in below code.然后您可以创建一个方法来解析该 JSONObject 并返回 Map 的列表,如下面的代码所示。

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);

    }
}

Just use GenSON .只需使用GenSON The function parseKeys(String json) returns HashMap. function parseKeys(String json)返回 HashMap。 The link for the lib: https://github.com/EvgeniGenchev/GenSON-lib I made the library for this specific use case.库的链接: https://github.com/EvgeniGenchev/GenSON-lib我为这个特定的用例制作了库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM