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

2022-09-03 04:33:23
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}

答案 1
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


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