Java List<Map<String,Object>> 到 org.json.JSONObject?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/512692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 15:36:15  来源:igfitidea点击:

List<Map<String,Object>> to org.json.JSONObject?

javajsonjavabeansmap

提问by yogman

List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();

map.put("abc", "123456");
map.put("def", "hmm");
list.add(map);
JSONObject json = new JSONObject(list);
try {
    System.err.println(json.toString(2));
} catch (JSONException e) {
    e.printStackTrace();
}

What's wrong with this code?

这段代码有什么问题?

The output is:

输出是:

{"empty": false}

回答by WolfmanDragon

You have a map nested inside a list. you are trying to call the Map without ever iterating through the list first. JSON sometimes feels like magic but in fact it is not. I'll post some code in a moment.
It would be more consistent with JSON to make a Map of Maps instead of a List of Maps.

您有一个嵌套在列表中的地图。您试图调用 Map 而不先遍历列表。JSON 有时感觉很神奇,但实际上并非如此。稍后我会发布一些代码。
制作地图的地图而不是地图的列表会更符合 JSON。

JSONObject json = new JSONObject(list);
Iterator<?> it = json.keys();
while (keyed.hasNext()) {
    String x = (String) it.next();
    JSONObject jo2 = new JSONObject(jo.optString(x));
}

回答by gavinandresen

You need to end up with a JSONArray (corresponding to the List) of JSONObjects (the Map).

您需要以 JSONObjects(地图)的 JSONArray(对应于列表)结束。

Try declaring the json variable as a JSONArray instead of a JSONObject (I believe the JSONArray constructor will do the right thing).

尝试将 json 变量声明为 JSONArray 而不是 JSONObject (我相信 JSONArray 构造函数会做正确的事情)。

回答by StaxMan

Also: you could consider using one of other parsers from json.org's list: most of them allow your Json "objects" and "arrays" to map natively to java.util.Maps and java.util.Lists; or in some cases to real Java objects too.

另外:您可以考虑使用 json.org 列表中的其他解析器之一:它们中的大多数允许您的 Json“对象”和“数组”本地映射到 java.util.Maps 和 java.util.Lists;或者在某些情况下也是真正的 Java 对象。

My recommendation would be Hymanson, http://Hymanson.codehaus.org/Tutorialwhich allows for mapping to List/Map/Integer/String/Boolean/null, as well as to real Beans/POJOs. Just give it the type and it maps data to you, or writes Java objects as Json. Others like "json-tools" from berlios, or google-gson also expose similar functionality.

我的建议是 Hymanson,http://Hymanson.codehaus.org/Tutorial,它允许映射到 List/Map/Integer/String/Boolean/null,以及真正的 Beans/POJO。只需给它类型,它就会将数据映射给您,或者将 Java 对象编写为 Json。其他像 berlios 的“json-tools”或 google-gson 也公开了类似的功能。

回答by Jose

This worked for me:

这对我有用:

List<JSONObject> jsonCategories = new ArrayList<JSONObject>();

JSONObject jsonCategory = null;

for (ICategory category : categories) {
    jsonCategory = new JSONObject();
    jsonCategory.put("categoryID", category.getCategoryID());
    jsonCategory.put("desc", category.getDesc());
    jsonCategories.add(jsonCategory);
}
try {
    PrintWriter out = response.getWriter();
    response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache");
    _log.info(jsonCategories.toString());
    out.write(jsonCategories.toString());

} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

回答by sivanza

List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();

map.put("abc", "123456");
map.put("def", "hmm");
list.add(map);
// it's wrong JSONObject json = new JSONObject(list);
// if u use list to add data u must be use JSONArray

JSONArray json = JSONArray.fromObject(list);
try {
    System.err.println(json.toString(2));
} catch (JSONException e) {
    e.printStackTrace();
}

回答by ShadowJohn

public String listmap_to_json_string(List<Map<String, Object>> list)
{       
    JSONArray json_arr=new JSONArray();
    for (Map<String, Object> map : list) {
        JSONObject json_obj=new JSONObject();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String key = entry.getKey();
            Object value = entry.getValue();
            try {
                json_obj.put(key,value);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                           
        }
        json_arr.put(json_obj);
    }
    return json_arr.toString();
}

alright, try this~ This worked for me :D

好吧,试试这个~这对我有用:D

回答by Flávio Ferreira

You can do it using both:

您可以使用两者来做到这一点:

JSONArraydirectly as,

JSONArray直接作为,

String toJson(Collection<Map<String, Object>> list)
{       
    return new JSONArray(list).toString();
}

Or by iterating the list with Java8 (like @ShadowJohn solution):

或者通过使用 Java8 迭代列表(如@ShadowJohn 解决方案):

String toJson(Collection<Map<String, Object>> list)
{       
    return new JSONArray( 
            list.stream()
                .map((map) -> new JSONObject(map))
            .collect(Collectors.toList()))
        .toString();
}

回答by Balaji Dubey

If you are using org.json.simple.JSONArray

如果您使用org.json.simple.JSONArray

(https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1)

https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1

List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("abc", "123456");
map.put("def", "hmm");
list.add(map);

JSONArray jsonArray = new JSONArray();
jsonArray.addAll(listOfMaps);