Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GSON parsing without a lot of classes

I have the following JSON and I'm only interested in getting the elements "status", "lat" and "lng".

Using Gson, is it possible to parse this JSON to get those values without creating the whole classes structure representing the JSON content?

JSON:

{
  "result": {
    "geometry": {
      "location": {
        "lat": 45.80355369999999,
        "lng": 15.9363229
      }
    }
  },
  "status": "OK"
}
like image 860
Reeebuuk Avatar asked May 16 '13 19:05

Reeebuuk


2 Answers

You don't need to define any new classes, you can simply use the JSON objects that come with the Gson library. Heres a simple example:

JsonParser parser = new JsonParser(); JsonObject rootObj = parser.parse(json).getAsJsonObject(); JsonObject locObj = rootObj.getAsJsonObject("result")     .getAsJsonObject("geometry").getAsJsonObject("location");  String status = rootObj.get("status").getAsString(); String lat = locObj.get("lat").getAsString(); String lng = locObj.get("lng").getAsString();  System.out.printf("Status: %s, Latitude: %s, Longitude: %s\n", status,         lat, lng); 

Plain and simple. If you find yourself repeating the same code over and over, then you can create classes to simplify the mapping and eliminate repetition.

like image 160
Perception Avatar answered Oct 11 '22 04:10

Perception


It is indeed possible, but you have to create a custom deserializer. See Gson documentation here and Gson API Javadoc here for further info. And also take a look at other reponses of mine here and here... and if you still have doubts, comment.

That said, in my opinion it is much easier for you to parse it creating the correspondent classes, even more taking into account the simplicity of your JSON response... With the usual approach you only have to write some super-simple classes, however, writing a custom deserializer, although is not that complex, it will take you probably longer, and it will be more difficult to adapt if later on you need some data else of your JSON...

Gson has a way of operating that has been designed for developers to use it, not for trying to find workarounds!

Anyway, why do you not want to use classes? If you don't like to have many classes in your project, you can just use nested classes and your project will look cleaner...

like image 24
MikO Avatar answered Oct 11 '22 05:10

MikO