簡體   English   中英

將<Map <String,Object >>列出到org.json.JSONObject?

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

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

這段代碼出了什么問題?

輸出是:

{"empty": false}
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();
}

好吧,試試這個〜這對我有​​用:D

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

您需要以JSONObjects(Map)的JSONArray(對應於List)結束。

嘗試將json變量聲明為JSONArray而不是JSONObject(我相信JSONArray構造函數會做正確的事情)。

這對我有用:

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

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

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

您有一個嵌套在列表中的地圖。 你試圖調用地圖而不先迭代列表。 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));
}

另外:你可以考慮使用json.org列表中的其他解析器之一:它們中的大多數允許你的Json“對象”和“數組”本地映射到java.util.Maps和java.util.Lists; 或者在某些情況下也是真正的Java對象。

我的建議是Jackson, http://jackson.codehaus.org/Tutorial ,它允許映射到List / Map / Integer / String / Boolean / null,以及真正的Beans / POJO。 只需給它類型並將數據映射到您,或者將Java對象寫為Json。 其他像berlios的“json-tools”或google-gson也暴露了類似的功能。

你可以使用兩者:

JSONArray直接作為,

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM