2013-09-24 13 views
94

Come posso creare un oggetto JSON come il seguente, in Java usando JSONObject?Come creare JsonArray corretto in Java usando JSONObject

{ 
    "employees": [ 
     {"firstName": "John", "lastName": "Doe"}, 
     {"firstName": "Anna", "lastName": "Smith"}, 
     {"firstName": "Peter", "lastName": "Jones"} 
    ], 
    "manager": [ 
     {"firstName": "John", "lastName": "Doe"}, 
     {"firstName": "Anna", "lastName": "Smith"}, 
     {"firstName": "Peter", "lastName": "Jones"} 
    ] 
} 

Ho trovato un sacco di esempi, ma non la mia esatta stringa JSONArray.

risposta

196

Ecco il codice utilizzando Java 6 per iniziare:

JSONObject jo = new JSONObject(); 
jo.put("firstName", "John"); 
jo.put("lastName", "Doe"); 

JSONArray ja = new JSONArray(); 
ja.put(jo); 

JSONObject mainObj = new JSONObject(); 
mainObj.put("employees", ja); 

Edit: Poiché non v'è stato un sacco di confusione su put vs add qui mi tenterà di spiegare la differenza. In Java 6 org.json.JSONArray contiene il metodo put e in Java 7 javax.json contiene il metodo add.

Un esempio di questo utilizzando il builder in Java 7 sembra qualcosa di simile:

JsonObject jo = Json.createObjectBuilder() 
    .add("employees", Json.createArrayBuilder() 
    .add(Json.createObjectBuilder() 
     .add("firstName", "John") 
     .add("lastName", "Doe"))) 
    .build(); 
+3

forse anche avvolgere in try/catch? (o il metodo deve avere una dichiarazione di tiri) – Lukas1

+6

JSONArray non ha un metodo put. – Jim

+1

usa add invece di put – CleanX

9

Suppongo che stai ricevendo questo JSON da un server o un file e si desidera creare un oggetto JSONArray fuori di esso.

String strJSON = ""; // your string goes here 
JSONArray jArray = (JSONArray) new JSONTokener(strJSON).nextValue(); 
// once you get the array, you may check items like 
JSONOBject jObject = jArray.getJSONObject(0); 

Spero che questo aiuti :)

Problemi correlati