views:

1112

answers:

2

Hi,

I'm requesting data from a server which returns data in the JSON format. Casting a HashMap into JSON when making the request wasn't hard at all but the other way seems to be a little tricky. The JSON response looks like this:

{ "header" : { "alerts" : [ { "AlertID" : "2",
            "TSExpires" : null,
            "Target" : "1",
            "Text" : "woot",
            "Type" : "1"
          },
          { "AlertID" : "3",
            "TSExpires" : null,
            "Target" : "1",
            "Text" : "woot",
            "Type" : "1"
          }
        ],
      "session" : "0bc8d0835f93ac3ebbf11560b2c5be9a"
    },
  "result" : "4be26bc400d3c"
}

What way would be easiest to access this data? I'm using the GSON module.

Cheers.

+1  A: 

JSONObject typically uses HashMap internally to store the data. So, you can use it as Map in your code.

Example,

JSONObject obj = JSONObject.fromObject(strRepresentation);
Iterator i = obj.entrySet().iterator();
while (i.hasNext()) {
   Map.Entry e = (Map.Entry)i.next();
   System.out.println("Key: " + e.getKey());
   System.out.println("Value: " + e.getValue());
}
Phanindra
+3  A: 

Use this data structure:

public class Data {
    private Header header;
    private String result;
    // Add/generate getters and setters.

    public static class Header {
        private List<Alert> alerts;
        private String session;
        // Add/generate getters and setters.
    }

    public static class Alert {
        private Long AlertID;
        private Object TSExpires;
        private Integer Target;
        private String Text;
        private Integer Type;
        // Add/generate getters and setters. 
        // PS: I would lowercase the property names in both JSON as this class.
    }
}

And use this oneliner to convert it back:

Data data = new Gson().fromJson(json, Data.class);
BalusC
Hi BalusC, This method seemed to work fine.....until I tried using it in a Java Applet and got hit with a `reflectpermission`. Damn. :( I've posted a question [here](http://stackoverflow.com/questions/2788017/). Thanks.
Mridang Agarwalla
@BalusC How do you access the alerts List once you've executed the fromJson line? What do the get functions look like?
rohanbk
@rohanbk: just conforming the javabean specs. `getPropertyName()` and so on. Any IDE can autogenerate them for you.
BalusC