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}
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.
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.
My recommendation would be Jackson, http://jackson.codehaus.org/Tutorial which 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.
This worked for me:
alright, try this~ This worked for me :D
You can do it using both:
JSONArray
directly as,Or by iterating the list with Java8 (like @ShadowJohn solution):