0

I have an app that does some authentication using Google Accounts. As a response to my request , Google sends the following JSON

{ "id": "ID", "name": "NAME", "given_name": "GiVEN NAME", "family_name": "FAMILY_NAME", "link": "https://plus.google.com/ID", "picture": "https://PHOTO.jpg", "gender": "GENDER", "locale": "LOCALE" }

The problem is that many google accounts don't have all those details filled out. So in most cases the JSON looks like

{ "id": "ID", "locale": "LOCALE" }

So in order to get the data I need, I need to check each JSON to see if the name,picture,gender etc. are provided and if not, prompt the user to enter those data items.To do this I tried checking if the JSONObject.getString("name") etc. was null. But instead of completing the if condition, the app skips to an JSON exception.

So what I need is a way to add the JSON data Google sends me to an Associative Array with the keys and values and check through that array to see if the data I need is there without getting an JSON exception.Do you know any way of doing that?

Sorry for my bad english.

2
  • see following link json.org/javadoc/org/json/… Commented Aug 22, 2013 at 11:00
  • You seem to have some problems with some code that you have written, but your description of your problem doesn't make much sense. Please include the relevant part of the code AND the exception message and stack trace for the exception. Commented Aug 22, 2013 at 11:07

6 Answers 6

3

You can use JSONObject.optString(String)

if ( "".equals( jsonObject.optString("name") ) ) {
    // name is not present
}

As per Javadoc:

public String optString (String name)

Returns the value mapped by name if it exists, coercing it if necessary. Returns the empty string if no such mapping exists.

Sign up to request clarification or add additional context in comments.

Comments

0

You can check that using:

if(JSONObject.has("name"))
{

}
else
{

}

1 Comment

Yeah it seems to work very well.thank you.I've marked this as the answer
0

see the answer at stack-over flow: JSON to multidimentional array in android/java

hope this will help you

Comments

0

To check if JSON has specific field use

jsonObject.has("NAME")

if it returns true simply add this field by jsonObject.getString("NAME") when it returns false prompt to add this field.

Maybe use Gson library? It uses reflection to cast JSON to java classes. You don't need to check if JSON contains specific field or not.

Comments

0

It might be long but you can put each of these "JSONObject.getString("name")" in different try catch and you can define a default value or null in catch.

Comments

0

I use GSON for JSON parsing it's very easy to implement and very effective parsing long and complex responses.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.