2012-08-27 39 views
21

Busqué mucho en Google hoy para este tema. Pero no puedo encontrarlo, ¿cómo puedo agregar un JSONArray a un JSONObject?Agregar JsonArray a JsonObject

porque cada vez que lo hago me sale este error: Stackoverflow

 JSONObject fillBadkamerFormaatFromContentlet(Structure structure, String formaat) { 
    JSONObject jsonObject = new JSONObject(); 
    JSONArray arr = new JSONArray(); 

    BadkamerFormaat badkamerFormaat = new BadkamerFormaat(); 
    BadkamerTegel badkamerTegel; 
    List<Contentlet> contentlets = getContentletsByStructure(structure); 
    badkamerFormaat.formaat = formaat; 
    badkamerFormaat.tegels = new ArrayList<BadkamerTegel>(); 

    try { 
     jsonObject.put("formaat", formaat); 
    } catch (JSONException e1) { 
     throw new RuntimeException(e1); 
    } 

    for(Contentlet contentlet : contentlets) { 
     badkamerTegel = new BadkamerTegel(); 
     badkamerTegel.naam = contentlet.getStringProperty(ParameterNames.toolBetegelVeldNaam); 
     try { 
      badkamerTegel.afbeeldingTegel = contentlet.getBinary(ParameterNames.toolBetegelVeldTegelAfbeelding).getPath(); 
      badkamerTegel.afbeeldingBadkamer = contentlet.getBinary(ParameterNames.toolBetegelVeldBadkamerAfbeelding).getCanonicalPath(); 
      arr.put(badkamerTegel.toJSON()); 
     } catch (IOException e) { 
      throw new RuntimeException(e); 
     } 
    } 

    try { 
     jsonObject.put("aoColumnDefs",arr); 
    } catch (JSONException e) { 
     throw new RuntimeException(e); 
    } 

    return jsonObject;   
} 

me sale este error:

java.lang.StackOverflowError 
at com.dotmarketing.util.json.JSONArray.<init>(JSONArray.java:248) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 
at com.dotmarketing.util.json.JSONObject.put(JSONObject.java:953) 

El JSON que quiero: Sólo el último JSONArray va mal:

{ 
      "wand": [ 
     { 
      formaat: 'vierkant15x15' 
      tegels: [ 
        {naam: '', imgThumb: '/bla/bla.png', largeImg: '/bla/bla2.png'} 
        ,{naam: '', imgThumb: '/bla/bla.png', largeImg: '/bla/bla2.png'} 
        ] 
     } 
     , 

     { 
      formaat: 'vierkant17x15' 
      tegels: [ 
        {naam: '', imgThumb: '/bla/bla.png', largeImg: '/bla/bla2.png'} 
        ,{naam: '', imgThumb: '/bla/bla.png', largeImg: '/bla/bla2.png'} 
        ] 
     } 
    ] 

, "vloer": [ { formaat: 'vierkant10x15' tegels: [ {naam: '', imgThumb: '/bla/bla.png', largeImg: '/bla/bla2blaje.png'} , {naam: '', imgThumb: ' /bla/bla.png', largeImg: '/bla/bla2.png'} ] } ,

 { 
      formaat: 'vierkant45x15' 
      tegels: [ 
        {naam: '', imgThumb: '/bla/bla.png', largeImg: '/bla/bla2.png'} 
        ,{naam: '', imgThumb: '/bla/bla.png', largeImg: '/bla/bla2.png'} 
        ] 
     } 
    ] 

}

+0

Hmm .. ¡También la persona que contestó él, su opción no funcionó para mí! – Gynnad

+1

Creo que puede ser un error en la json impl que está utilizando. parece que está utilizando la API correctamente desde el código que ha proporcionado. – jtahlborn

Respuesta

32

Creo que es un problema (aka. error) con el API que está utilizando. JSONArray implementa Collection (la implementación de json.org de la que se deriva esta API hace no tiene JSONArray implementar Colección). Y JSONObject tiene un método put() sobrecargado que toma una Colección y lo envuelve en un JSONArray (causando el problema). Creo que es necesario para forzar el otro método JSONObject.put() a utilizar:

jsonObject.put("aoColumnDefs",(Object)arr); 

debe presentar un error con el vendedor, bastante seguro de su método JSONObject.put(String,Collection) está roto.

+0

¡Gracias, esta es la solución! :) – Gynnad

+0

muy buena ... solución ... –

20

aquí es simple código

List <String> list = new ArrayList <String>(); 
list.add("a"); 
list.add("b"); 
JSONArray array = new JSONArray(); 
for (int i = 0; i < list.size(); i++) { 
     array.put(list.get(i)); 
} 
JSONObject obj = new JSONObject(); 
try { 
    obj.put("result", array); 
} catch (JSONException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} 
pw.write(obj.toString()); 
+0

¿Qué es pw no decleare? –

+0

Objeto PrintWriter –

1

estoy empezando a aprender acerca de esto mismo, siendo muy nuevo en el desarrollo de Android y me encontré con este video muy útil.

https://www.youtube.com/watch?v=qcotbMLjlA4

Se cubre específicamente para conseguir JSONArray a JSONObject a las 19:30 en el video.

Código del vídeo para JSONArray a JSONObject:

JSONArray queryArray = quoteJSONObject.names(); 

ArrayList<String> list = new ArrayList<String>(); 

for(int i = 0; i < queryArray.length(); i++){ 
    list.add(queryArray.getString(i)); 
} 

for(String item : list){ 
    Log.v("JSON ARRAY ITEMS ", item); 
} 
0

Usted simplemente puede hacerlo utilizando JSON biblioteca simple. Aquí es el Gradle

compile 'com.googlecode.json-simple:json-simple:1.1'

Aquí es código de ejemplo:

org.json.simple.JSONObject jsonObject=new org.json.simple.JSONObject(); 
jsonObject.put("Object","String Object"); 

ArrayList<String> list = new ArrayList<String>(); 
      list.add("john"); 
      list.add("mat"); 
      list.add("jason"); 
      list.add("matthew"); 

      jsonObject.put("List",list); 

Eso es todo.:)

+0

¿Cómo recuperar los nombres de la matriz almacenados en el objeto JSON? –

2

su lista:

List<MyCustomObject> myCustomObjectList; 

Su JSONArray:

// Don't need to loop through it. JSONArray constructor do it for you. 
new JSONArray(myCustomObjectList) 

Su respuesta:

return new JSONObject().put("yourCustomKey", new JSONArray(myCustomObjectList)); 

cuerpo de la solicitud HTTP POST/venta será así:

{ 
     "yourCustomKey: [ 
      { 
       "myCustomObjectProperty": 1 
      }, 
      { 
       "myCustomObjectProperty": 2 
      } 
     ] 
    } 
Cuestiones relacionadas