Reputation: 1777
I am trying to fetch value of "formatted_phone_number" but every time it returns null. Though it works for some keys like "formatted_address".
I am using org.json.JSONObject
This is my code -
JSONObject jObject = null;
String result = null;
try {
jObject = new JSONObject(jsonData);
JSONObject jObjectResult = (JSONObject) jObject.get("result");
result = jObjectResult.getString("formatted_phone_number");
} catch (JSONException e) {
} catch (Exception e) {
}
}
Sample JSON Data - https://developers.google.com/places/web-service/details
Let me know what I am doing wrong here and also is there any better way for this?
Upvotes: 0
Views: 692
Reputation: 60081
I wrote the code as your question, and use the JSON as per the link. They works perfectly fine. Suggest you debug your input jsonData
data content.
Anyway, for using GSON, it's as below (based your the JSON format you are checking.
Define the class model object matching the JSON
public class MyData {
Result result;
Result getResult() {
return result;
}
}
public class Result {
String formatted_phone_number;
String getPhone() {
return formatted_phone_number;
}
}
And then use it as below.
MyData mydata = new Gson().fromJson(jsonData, MyData.class);
String myPhone = mydata.getResult().getPhone();
You'll get the data auto parsed into your object. As you expand your class model structure (e.g. formatted_address, rating etc), you'll magically get them as well. Hope this ease your job. Cheers!
Upvotes: 2