views:

109

answers:

2

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!

A: 

have you try GSon ? it is specialized in Java Object to JSon and Json to Java Object.

rsilva
gson does the job very well, thanks @rsilva ! nevertheless, I wonder if json.org's api is OK?
k.honsali
A: 

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.

StaxMan
OK 4 http://jackson.codehaus.org/ As for json.org, I have no attachment to it...yet...@API, JSONArray produces JSONObjects from a map in a different way (no brackets) than the manual creation of a JSONObject from a map.
k.honsali
ok (wrt creating maps), haven't used it extensively. Too bad if it is asymmetric. But note that brackes are not part of object model, but of serialization... I guess what you are saying is that it adds all elements of Map or List, not the Map or List itself. In Java that is generally due to difference between List.add() and List.addAll() (or Map.put(), Map.putAll()).
StaxMan