Siddharth
Siddharth

Reputation: 9574

Json parsing gives NullPointerException

I am calling this url

http://maps.googleapis.com/maps/api/geocode/json?latlng=18.550455,73.920148&sensor=true

And getting a response (I have deleted a lot of the response from the middle since its not relevant for the question.

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Towards Wadgao Sheri",
               "short_name" : "Towards Wadgao Sheri",
               "types" : [ "route" ]
            },
            {
               "long_name" : "411014",
               "short_name" : "411014",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "Towards Wadgao Sheri, Sainikwadi, Wadgaon Sheri, Pune, Maharashtra 411014, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 18.55131630,
                  "lng" : 73.91882219999999
               },
               "southwest" : {
                  "lat" : 18.55024130,
                  "lng" : 73.91866569999999
               }
            },
            "location" : {
               "lat" : 18.55077720,
               "lng" : 73.91878240
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 18.55212778029150,
                  "lng" : 73.92009293029150
               },
               "southwest" : {
                  "lat" : 18.54942981970850,
                  "lng" : 73.91739496970848
               }
            }
         },
         "types" : [ "route" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "Sainikwadi",
               "short_name" : "Sainikwadi",
               "types" : [ "neighborhood", "political" ]
            },
            {
               "long_name" : "411014",
               "short_name" : "411014",
               "types" : [ "postal_code" ]
            }
         ],
         "formatted_address" : "Sainikwadi, Wadgaon Sheri, Pune, Maharashtra 411014, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 18.5551140,
                  "lng" : 73.92143690
               },
               "southwest" : {
                  "lat" : 18.5465270,
                  "lng" : 73.91406809999999
               }
            },
            "location" : {
               "lat" : 18.55092520,
               "lng" : 73.91687659999999
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 18.5551140,
                  "lng" : 73.92143690
               },
               "southwest" : {
                  "lat" : 18.5465270,
                  "lng" : 73.91406809999999
               }
            }
         },
         "types" : [ "neighborhood", "political" ]
      },
      {
         "address_components" : [
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 35.50447520,
                  "lng" : 97.3955550
               },
               "southwest" : {
                  "lat" : 6.747138899999999,
                  "lng" : 68.16238590
               }
            },
            "location" : {
               "lat" : 20.5936840,
               "lng" : 78.962880
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 35.50447520,
                  "lng" : 97.3955550
               },
               "southwest" : {
                  "lat" : 6.747138899999999,
                  "lng" : 68.16279560
               }
            }
         },
         "types" : [ "country", "political" ]
      }
   ],
   "status" : "OK"
}

Code

        JsonObject response = new JsonObject().getAsJsonObject(jsonResults.toString());
>>>NPE  JsonArray results = response.getAsJsonArray("results");

The response from json is in jsonResults. I am getting a NPE on the 2nd line

I guess response is null, I wonder why, what am doing wrong here ? Just created a json object out of the response json. I know I am missing something really silly here.

Edit :

Exception in thread "Thread-0" java.lang.NullPointerException
    at com.mcruiseon.ivr.God.getGeoAddress(God.java:141)

Edit 2 :

I have edited the json response a bit. Please note. Also I am trying to extract formatted_address

Edit 3 :

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

Upvotes: 1

Views: 9449

Answers (2)

Brian Roach
Brian Roach

Reputation: 76888

You start off with ...

JsonObject response = new JsonObject().getAsJsonObject(jsonResults.toString());

This makes no sense. You've created a new, empty JsonObject then attempt to retrieve an element from it using your entire JSON string as the property name. Therefore, yes ... response is null.

Your JSON is an object. It contains two fields; results which is an array of objects and status which is a String.

Normally when using Gson you'd create matching Java classes and use a Gson instance to deserialize to them. If you don't want to do that, then you'd Gson's JsonParser to parse the Json and then access it through the various Json* classes:

/// jsonResuts is a String containing the JSON you list.
JsonObject obj = new JsonParser().parse(jsonResults).getAsJsonObject();
JsonArray resultsArray = obj.getAsJsonArray("results");

Now you have the array of objects and can delve deeper into that using the same methods/classes from Gson I used above.

for (JsonElement e : resultsArray) {
    JsonObject resultsObj = e.getAsJsonObject();
    JsonElement formattedAddress = resultsObject.get("formatted_address");
    String addressAsString = formattedAddress.getAsString();
    System.out.println(addressAsString);
    // The above can be chained and reduced to one line:
    // System.out.println(e.getAsJsonObject().get("formatted_address").getAsString());
}  

Upvotes: 1

Raghunandan
Raghunandan

Reputation: 133560

Key to the answer : Gson or not, parsing the json string is the key to the answer.

From the comments by Siddharth below.

JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonResults.toString()).getAsJsonObject() ; 
JsonArray results = json.getAsJsonArray("results");
JsonObject result = results.get(0).getAsJsonObject(); 
customerAddress = result.get("formatted_address").getAsString(); 

Alternative :

I failed to read the edit 3 part of the question and failed to look at the gson tag. So i ended up providing the below alternative.

JSONObject jsono = new JSONObject (myjsonstring);
JSONArray myListsAll= new JSONArray(jsono.getString("results"));
for(int i=0;i<myListsAll.length();i++){
JSONObject jsonObject1 = (JSONObject) myListsAll.get(i);
JSONArray myarray= new JSONArray(jsonObject1.getString("address_components"));
for(int i1=0;i1<myarray.length();i1++)
{
JSONObject jsonobject2 =  myarray.getJSONObject(i1);                     
System.out.println(""+jsonobject2.getString("long_name"));                  
System.out.println(""+jsonobject2.getString("short_name"));
System.out.println(""+jsonobject2.getString("types"));
}
}

Output

Towards Wadgao Sheri
Towards Wadgao Sheri
["route"]
Sainikwadi
Sainikwadi
["neighborhood","political"]
Wadgaon Sheri
Wadgaon Sheri
["sublocality","political"]
Pune
Pune
 ["locality","political"]
 Pune
 Pune
 ["administrative_area_level_2","political"]
Maharashtra
MH
["administrative_area_level_1","political"]
India
IN
["country","political"]
411014
411014
["postal_code"]
 Sainikwadi
 Sainikwadi
 ["neighborhood","political"]
 Wadgaon Sheri
 Wadgaon Sheri
 ["sublocality","political"]
 Pune
 Pune
 ["locality","political"]
 Pune
 Pune
 ["administrative_area_level_2","political"]
 Maharashtra
 MH
 ["administrative_area_level_1","political"]
 India
 IN
 ["country","political"]
 411014
 411014
 ["postal_code"]
 Wadgaon Sheri
 Wadgaon Sheri
 ["sublocality","political"]
 Pune
 Pune
 ["locality","political"]
 Pune
 Pune
 ["administrative_area_level_2","political"]
 Maharashtra
 MH
 ["administrative_area_level_1","political"]
 India
 IN
 ["country","political"]
 411014
 411014
 ["postal_code"]
 Pune
 Pune
 ["administrative_area_level_2","political"]
 Maharashtra
 MH
 ["administrative_area_level_1","political"]
 India
 IN
 ["country","political"]
 Pune
 Pune
 ["locality","political"]
 Pune
 Pune
 ["administrative_area_level_2","political"]
 Maharashtra
 MH
 ["administrative_area_level_1","political"]
 India
 IN
 ["country","political"]
 Pune
 Pune
 ["administrative_area_level_2","political"]
 Maharashtra
 MH
 ["administrative_area_level_1","political"]
 India
 IN
 ["country","political"]
 Maharashtra
 MH
 ["administrative_area_level_1","political"]
 India
 IN
 ["country","political"]
 India
 IN
 ["country","political"]

Upvotes: 2

Related Questions