2013-09-01 9 views
6
// JSON object to hold the information, which is sent to the server 
JSONObject jsonObjSend = new JSONObject(); 
jsonObjSend.put("action", "myAction"); 
jsonObjSend.put("type", tipo); 

Per ora è tutto ok, ma se voglio aggiungereAndroid JSONObject: aggiungere Array per il metodo put

jsonObjSend.put("elementi", arrayOfElements); 

dove arrayOf elementi devono essere un array di stringhe. Come posso fare?

/** EDIT

esempio di quello che ho bisogno

{ 
    "action": "myAction", 
    "type": "elementi", 
    "elementi": [ 
    "3287498357", 
    "23472857" 
    ] 
} 

risposta

27

Dopo aver visto l'esempio che ho capito che si sta cercando di fare qualcosa di simile, come ha chiesto in Java JsonObject array value to key

jsonObjSend.put("elementi", new JSONArray(new Object[] { "value1", "value2", "value3"})); 

Per semplificare:

JSONArray arr = new JSONArray(); 
arr.put("value1"); 
arr.put("value2"); 
//... 
jsonObjSend.put("elementi", arr); 
+1

Penso che non sia la soluzione per il mio problema. Aggiungo un esempio di ciò di cui ho bisogno. Guarda. Grazie –

+1

Ohh ho frainteso. Scuse. Guarda l'aggiornamento. –

+1

Grazie mille! Ora capisco! –

0
JSONObject jsonBody = new JSONObject(); 
jsonBody.put("action", "myAction"); //action is your string 
jsonBody.put("type", "elementi"); 
JSONArray arr = new JSONArray(); 
JSONObject elementi= new JSONObject(); 
itemList.put("id", id); 
itemList.put("name", name); 
arr.put(elementi); 
jsonBody.put("elementi", arr); 
+1

Sarebbe meglio se spiegassi perché il tuo codice funzionerebbe. –

+0

Funzionerà se si vuole creare una matrice all'interno dell'oggetto e sì funziona per me! – vineet