Reputation: 726
Salaam,
Using json.org API, we can easily convert a map to a JSON object :
Map<String, String> carta = new Map<String, String>();
carta.put( "id", "123");
carta.put( "Planet", "Earth");
carta.put( "Status", "getting dirty");
JSONObject json = new JSONObject();
for(Iterator<String> it=input.keySet().iterator(); it.hasNext();){
String key = it.next();
json.put(key, input.get(key));
}
System.out.println(json.toString());
// output: {id:"123", Planet:"Earth", Status: "getting dirty"}
Now we want to have an array of these object The API doesn't provide this does it?
At least, adding JSONObjects to a JSONArray removes the brackets :
JSONArray joArr = new JSONArray();
joArr.put( cartaEarth );
joArr.put( cartaMars );
System.out.println( joArr.toString() );
//output: [{ id:123, Planet:Earth, Status: getting dirty }, {id: 456, Planet:Mars, Status: maybe aliens there }]
without brackets...while in the API they mention:
put(java.util.Map value)
Put a value in the JSONArray, where the value will be a JSONObject which is produced from a Map.
instead of doing it byhand, preferred to discuss it first, thanks in advance!
Upvotes: 1
Views: 4708
Reputation: 116580
I would recommend looking at something else than org.json package. Pretty much all alternatives from org.json list provide more convenient and simpler ways to work with JSON. Aside from Gson that some like, I would recommend Jackson; and flex-json and Svenson are other packages that seem decent.
If you insist on doing this using org.json, you need to explain your problem bit more -- API has all the methods you need, and they do allow you to add values of all types (JSON arrays, objects, strings, numbers, booleans and nulls). But your types need to match JSON types, so there are no conversions from arrays to objects, for example.
Upvotes: 0