Android Parse Google Places API JSON - android

I'm trying to take the information from the JSON returned by Google Places.
jsonObj = new JSONObject(data);
JSONArray results = jsonObj.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
System.out.println(result.getString("name"));
if (result.getJSONArray("reviews") != null){
JSONArray reviewsArray = result.getJSONArray("reviews");
JSONObject reviews = reviewsArray.getJSONObject(0);
if (reviews != null){
String review = reviews.getString("text");
Log.d("tag", "review: " + review);
}
}
}
My question is, how can I make sure the either "name" or "reviews" are available to parse? that if (result.getJSONArray("reviews") != null) still fails because getJSONArray is empty.

You can do this by using the opt commands instead of the get commands. Change the get json array to the following:
(result.optJSONArray("reviews") != null)
Check out the JSONObject documentation for a complete list. You can also use the JSONObject has(String name) command to check if it exists before actually getting it.

Since your json is initially in the form of a JSONObject, you could use it's isNull(String name) helper method to check if a mapping exists and isn't null.
From the documentation:
isNull(String name) Returns true if this object has no mapping for
name or if it has a mapping whose value is NULL.
For example:
try {
jsonObj = new JSONObject(data);
if(!jsonObj.isNull("results")){
JSONArray results = jsonObj.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
if(!result.isNull("name"){
System.out.println(result.getString("name"));
}
if (result.getJSONArray("reviews") != null){
JSONArray reviewsArray = result.getJSONArray("reviews");
JSONObject reviews = reviewsArray.getJSONObject(0);
if (reviews != null){
String review = reviews.getString("text");
Log.d("tag", "review: " + review);
}
}
}
}
} catch(JSONException e){
//Something went wrong
}

Related

android convert a json object

In my android app, I am creating a function to convert to json object.
this is the code
JSONArray jsonArr = new JSONArray();
for (Modificateurs mod : this.getModificateurs()) {
JSONObject pnObj = new JSONObject();
pnObj.put(Artifact.JSON_MODIFICATEUR, mod.getModificateur());
pnObj.put(Artifact.JSON_DATEMODIFICATION, mod.getDateModification());
jsonArr.put(pnObj);
}
object.putOpt(Artifact.JSON_MODIFICATEURS, jsonArr);
Now i create this function to convert this json object but it still not working.
JSONArray jsonArr = object.getJSONArray(Artifact.JSON_MODIFICATEURS);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject objet = jsonArr.getJSONObject(i);
String modificateur = objet.optString(Artifact.JSON_MODIFICATEUR);
String date = objet.optString(Artifact.JSON_DATEMODIFICATION);
Modificateurs mod = new Modificateurs(modificateur, date);
mods.add(mod);
}
this.modificateurs=mods;
What's wrong in my function?
Regarding the comments, if your application crashes at line
for (Modificateurs mod : this.getModificateurs()) {
I guess it's a NullPointerException and this.getModificateurs() is returning null.
You have to check the nullity before iterating :
if (this.getModificateurs() != null) {
for (Modificateurs mod : this.getModificateurs()) {
...

How to Fetch Records from JSON Having the Same Name into Android's java file

[{"UserID":"vishi"},{"UserID":"vish"}]
this is the json data that I am sending from php...
how can i get these values with same name in android
Thanks,
JSONArray array = new JSONArray(...);
int length = array.length() ;
for (int i = 0; i < length; i++) {
JSONObject obj = array.optJSONObject(i);
if (obj != null) {
String userId = obj.optString("UserID");
}
}
[
{
"UserID": "vishi" // key is UserId. value is vishi
},
{
"UserID": "vish"
}
]
The key UserID is the same. Just loop through the array and get the value
ArrayList<String> list = new ArrayList<String>();
JSONArray jr = new JSONArray("your json");
for(int i=0i<jr.length();i++)
{
JSONObject jb = jr.getJSONObject(i);
String value= jb.getString("UserID");
list.add(value);
}
Note:
Blackbelt's answer will also work and it also has null check cause optJSONObject() could return null also. This is a better way
Drawing from blackbelt's answer
JSONObject obj = array.optJSONObject(i);
if (obj != null) {
String userId = obj.optString("UserID");
}
From the docs
public JSONObject optJSONObject (String name)
Added in API level 1
Returns the value mapped by name if it exists and is a JSONObject. Returns null otherwise.

data from a jsonobject in android

The below is called from a string url and returns a json object which has an json array inside, but something else is not working, can anyone show me how to access the data inside?
{"data":[{"8196":{"booking_id":"8150","client_id":"107","venue_id":null}}]
String jsonStr = "{\"data\":[{\"8196\":{\"booking_id\": \"8150\",\"client_id\": \"107\",\"venue_id\": null}}]}";
try {
JSONObject json = new JSONObject(jsonStr);
JSONArray array = json.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
Iterator it = o.keys();
while (it.hasNext()) {
String name = (String) it.next();
o = o.getJSONObject(name);
int bookingId = o.getInt("booking_id");
int clientId = o.getInt("client_id");
int venueId = o.optInt("venue_id");
Log.v("TEST", String.format("Booking ID: %s -- Client ID: %s -- Venue ID: %s", bookingId, clientId, venueId));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
I guess this is what you'll want. By the way, the JSON you posted is malformed. It's missing a } in the end.
You first need to decode the JSON string. The JSON sting you got in return is actually a serialized version of a JSON object.
You need to decode that string into a native Java Object.
There are a number of methods to this in Java. You can start by checking out the Java section at json.org.
I think the problem is that the value of key venue_id is null. You can replace null value with empty string(""), try it.

complex Json Parsing in Android

In my app, i want to parse json response which is in the format
{"quote":[{"orderId":"3209926"},{"totalpages":1}]}
below is the code which i had done,But the problem is how to get the "totalpages" value?
try {
JSONObject jObject = new JSONObject(result);
JSONArray jArray = jObject.getJSONArray("quote");
for (int i = 0; i < jArray.length(); i++)
{
JSONObject offerObject = jArray.getJSONObject(i);
current.orderId = offerObject.getInt("orderId");
It shows error when i use
current.totalpage= offerObject.getInt("totalpages");
Anybody knows how to parse this?THanks in advance
Note that getInt(), like other get-functions of JSONObject throw JSONException if the object does not contain the key requested. Thus, before you request the key you should use hasKey() to determine whether the object contains the key.
For example, inside the for loop you can do the following:
JSONObject offerObject = jArray.getJSONObject(i);
if(offerObject.has("orderId") {
current.orderId = offerObject.getInt("orderId");
}
if(offerObject.has("totalpages") {
current.totalpage= offerObject.getInt("totalpages");
}
You can also add a flag and a check after the loop to ensure that both orderId and totalpages were present in the JSON data.
I dont know why your json is having that structure. But if you want to parse it then you will have to do something like the following with the has function.
for (int i = 0; i < jArray.length(); i++) {
JSONObject offerObject = jArray.getJSONObject(i);
if(offerObject.has("orderId")) {
current.orderId = offerObject.getInt("orderId");
} else if(offerObject.has("totalpages")) {
current.totalpage= offerObject.getInt("totalpages");
}
}

Android: Decoding JSON

[{"placeID":"p0001","placeName":"INTI International University","placeType":"Education","placeLat":"2.813997","placeLng":"101.758229","placePict":""},{"placeID":"p0002","placeName":"Nilai International College","placeType":"Education","placeLat":"2.814179","placeLng":"101.7700107","placePict":""}]
How do I decode the JSON sent from my PHP script on Android?
please try this
String s = "[{\"placeID\":\"p0001\",\"placeName\":\"INTI International University\",\"placeType\":\"Education\","
+ "\"placeLat\":\"2.813997\",\"placeLng\":\"101.758229\",\"placePict\":\"\"},"
+ "{\"placeID\":\"p0002\",\"placeName\":\"Nilai International College\",\"placeType\":\"Education\",\"placeLat\":\"2.814179\",\"placeLng\":\"101.7700107\",\"placePict\":\"\"}]";
ArrayList<String> arrplaceID = new ArrayList<String>();
ArrayList<String> arrplaceName = new ArrayList<String>();
try {
JSONArray arr = new JSONArray(s);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonObject = arr.getJSONObject(i);
arrplaceID.add(jsonObject.optString("placeID"));
arrplaceName.add(jsonObject.optString("placeName"));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < arrplaceID.size(); i++) {
Log.e("arr[" + i + "] place Name", arrplaceName.get(i));
}
What is the problem in this Please Read this tutorial for parsing JSON it might be helpful in future also.json parsing link
Follow below points.
1) it seems the response you are getting is Json Array. so create one json array by response string.
JSonArray jArray = new JsonArray(responseString);
2) now you have your response in jArray. now iterate a loop and take json object from JsonArray, in your case you have two json objects.
for(i,i<jArray.size,i++)
{
JsonObject obj=jArray.get(i);
// here you got your first entry in jsonObject.
// nor use this obj according to ur need. you can say obj.getString("placeID");
// and so on.
}
refer this to understand more on json link
use JSONArray class:
JSONArray jsonplaces = new JSONObject(stringPlaces);
then your able to iterate throught array by using for-loop:
for (int i = 0; i < jsonplaces.length(); i++) {
JSONObject jsonplace = (JSONObject) jsonplaces.get(i);
//read items, for example:
String placeName = jsonplace.getString("placeName");
}

Categories

Resources