Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

What's wrong with this code?

The output is:

{"empty": false}
like image 941
yogman Avatar asked Feb 04 '09 18:02

yogman


People also ask

How do I pass a JSON object to a Map?

We need to use the JSON-lib library for serializing and de-serializing a Map in JSON format. Initially, we can create a POJO class and pass this instance as an argument to the put() method of Map class and finally add this map instance to the accumulateAll() method of JSONObject.

Can we convert Map to JSON?

We can convert a Map to JSON object using the toJSONString() method(static) of org. json. simple.

Can we convert JSON to Map in Java?

We can easily convert JSON data into a map because the JSON format is essentially a key-value pair grouping and the map also stores data in key-value pairs. Let's understand how we can use both JACKSON and Gson libraries to convert JSON data into a Map.

What is JSON object in Java with example?

A JSONObject is an unordered collection of key and value pairs, resembling Java's native Map implementations. Keys are unique Strings that cannot be null. Values can be anything from a Boolean, Number, String, or JSONArray to even a JSONObject. NULL object.


1 Answers

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

like image 55
ShadowJohn Avatar answered Sep 19 '22 01:09

ShadowJohn