2009-02-04 27 views
11
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(); 
} 

¿Qué pasa con este código?Lista <Map <String, Object >> to org.json.JSONObject?

La salida es:

{"empty": false} 

Respuesta

1

Tienes un mapa anidado dentro de una lista. está intentando llamar al Mapa sin repetir primero la lista. JSON a veces se siente mágico, pero de hecho no lo es. Voy a publicar un código en un momento.
Sería más consistente con JSON hacer un Mapa de Mapas en lugar de una Lista de Mapas.

JSONObject json = new JSONObject(list); 
Iterator<?> it = json.keys(); 
while (keyed.hasNext()) { 
    String x = (String) it.next(); 
    JSONObject jo2 = new JSONObject(jo.optString(x)); 
} 
2

Necesitas terminar con un JSONArray (correspondiente a la lista) de JSONObjects (el mapa).

Intente declarar la variable json como JSONArray en lugar de JSONObject (creo que el constructor JSONArray hará lo correcto).

+0

¿Qué pasa con el caso donde hay un JavaBean, que contiene una colección que contiene elementos Map, y me gustaría tener el nuevo JSONObject (myJavaBean)? Lo intenté y no estaba satisfecho. – yogman

1

También: podría considerar usar uno de los otros analizadores de la lista de json.org: la mayoría de ellos permiten que sus "objetos" y "arreglos" de Json se mapeen de forma nativa a java.util.Maps y java.util.Lists; o en algunos casos también a objetos reales de Java.

Mi recomendación sería Jackson, http://jackson.codehaus.org/Tutorial que permite mapear a List/Map/Integer/String/Boolean/null, así como a Beans/POJOs reales. Simplemente dele el tipo y le asigna datos, o escribe objetos Java como Json. Otros como "json-tools" de berlios o google-gson también exponen una funcionalidad similar.

1

Esto funcionó para mí:

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

Por favor, escriba un comentario a su código. – CSchulz

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

bien, probar este ~ Esto funcionó para mí: D

+2

Es '12 y estoy buscando la respuesta :) Estoy buscando algo muy similar a esto (particularmente una lista de matrices de HashMaps) y esto está ayudando considerablemente. –

0

Puede hacerlo utilizando tanto:

JSONArray directamente como,

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

O por iteración la lista con Java8 (como solución @ShadowJohn):

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