17
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}
CSchulz
  • 10,882
  • 11
  • 60
  • 114
yogman
  • 4,021
  • 4
  • 24
  • 27

8 Answers8

25
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

ShadowJohn
  • 251
  • 3
  • 3
  • 2
    It's '12 and I'm looking at the answer :) I'm looking at making something very similar to this (particularly an ArrayList of HashMaps) and this is helping out considerably. –  Aug 24 '12 at 18:59
4
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();
}
CSchulz
  • 10,882
  • 11
  • 60
  • 114
sivanza
  • 41
  • 1
3

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

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

gavinandresen
  • 551
  • 1
  • 4
  • 11
  • What about the case where there is a JavaBean, which contains a collection that contains Map elements, and I would like to new JSONObject(myJavaBean)? I tried and wasn't satisfied. – yogman Feb 04 '09 at 22:31
2

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.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
1

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();
}
CSchulz
  • 10,882
  • 11
  • 60
  • 114
Jose
  • 11
  • 1
1

If you are using 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);
Balaji Dubey
  • 446
  • 5
  • 10
1

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.

JSONObject json = new JSONObject(list);
Iterator<?> it = json.keys();
while (keyed.hasNext()) {
    String x = (String) it.next();
    JSONObject jo2 = new JSONObject(jo.optString(x));
}
CSchulz
  • 10,882
  • 11
  • 60
  • 114
WolfmanDragon
  • 7,851
  • 14
  • 49
  • 61
0

You can do it using both:

JSONArray directly as,

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

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

String toJson(Collection<Map<String, Object>> list)
{       
    return new JSONArray( 
            list.stream()
                .map((map) -> new JSONObject(map))
            .collect(Collectors.toList()))
        .toString();
}
martianwars
  • 6,380
  • 5
  • 35
  • 44