Handling null in JSONObject - android

My app uses Eventbrite API and it crashes when event logo is null.
JSONObject jsonRootObject = new JSONObject(event);
JSONArray jsonArray = jsonRootObject.optJSONArray("events");
JSONObject jsonObject = jsonArray.getJSONObject(i);
information = jsonObject.getJSONObject("logo");
text = information.getString("url");
name = "eventsImage" + i;
resId = getResources().getIdentifier(name, "id", getPackageName());
new LoadImagefromUrl().execute(new LoadImagefromUrlModel(text, resId));
I am trying to make exception for this event, but I am not very experienced with JSONObjects and I don't know how if statement should look like
I have tried the following, but it didn't work
jsonObject.getJSONObject("logo")!=null

You have to catch JSONException in
information = jsonObject.getJSONObject("logo");
like
try{
information = jsonObject.getJSONObject("logo");
}catch(JSONException je){
//json object not found
}
See this link
which says - public JSONObject getJSONObject (String name)
Returns the value mapped by name if it exists and is a JSONObject, or throws otherwise.
OR, You can use optJSONObject like this -
if(jsonObject.optJSONObject("logo")!=null)'
Because optJSONObject doesn't throws exceptions instead returns null if no key found

It crashes because you are trying to retrieve an object that does not exist. If object might be null you should be using jsonObject.optJsonObject("logo") instead.

Related

Trouble accessing an array of JSON objects

I'm fairly new to Android Studio and Java, and I'm working on an app that takes data from Unsplash's API and displays it. However, I'm getting a JSON typeMismatch error, and I'm not sure how to correctly extract the data. Technically I'm getting back an array of JSONObjects, but I'm finding that simply changing JSONObject to JSONArray is not the correct approach.
I believe the problem is with the following lines of code: What I want to do is get the user (photographer) name and profile image, and the image they're posting.
Any help is greatly appreciated!
private NewPhotos getNewPhotos(String jsonData) throws JSONException {
JSONObject unsplash = new JSONObject(jsonData);
JSONObject user = unsplash.getJSONObject("user");
return new NewPhotos();
}
This is the JSON I'm getting back
This is the error message
You need first, cast JSON ARRAY.
You didn't put all json file, but it seems to be an array first.
private NewPhotos getNewPhotos(String jsonData) throws JSONException {
JSONArray unsplash = new JSONArray(jsonData);
for (int i = 0; i < unsplash.length(); i++) {
JSONObject jsonObj = (JSONObject) unsplash.get(i);
JSONObject user = jsonObj.getJSONObject("user");
// Do something with user
}
// Your implementation
return new NewPhotos();
}
This doesn't work for you? :
JSONObject unsplash = new JSONObject(jsonData);
JSONArray user = unsplash.getJSONArray("user");
Cause in your code you're trying to assign jsonArray to jsonObject.
You can't convery JSON Array into a Json object. Rafaela is right. You need to pass the string in Json array and then loop through each object to access user json.

Android, Iterate over JSON-fied dictionary

I have the following string, which was created using javascript JSON. (It's passed from a Webview to the native code using JavascriptInterface.)
{"var1":1,"var2":8}
How do I convert that into an object and then iterate over the key/value pairs? The names of the keys are NOT known in advance.
I have seen this JSON Array iteration in Android/Java and this Converting json string to java object? and this how to convert JSON string to object in JAVA android.
None of those seem to fit with my example, which is a dictionary with unknown key names. At least, it's certainly not clear to me which of the 15+ answers is relevant for my case.
The org.json library comes "for free" with Android, so I'd go with that. Usage when you don't know the keys ahead of time could be something like this:
try {
JSONObject jsonObject = new JSONObject(/* your json String here */);
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = jsonObject.getString(key);
// do whatever you want with key/value
}
}
catch (JSONException e) {
// thrown when:
// - the json string is malformed (can't be parsed)
// - there's no value for a requested key
// - the value for the requested key can't be coerced to String
}
You can use it by converting the getting the json length like this:-
JSONObject obj = new JSONObject(response);
for (int i = 0; i < obj.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject heroObject = obj.getJSONObject(i);
String aka=heroObject.getString("your key here");
}

How to use single word as JSON data in android?

I am trying to extract the JSON data which is just a single word. I have used JSON Array when it was a long list of a set of data but this time it just a word like - done or failed.
My Code is -
JSONObject jsonObject = new JSONObject(s);
//JSONArray jsonArray = jsonObject.getJSONArray("contacted");
loggingTest = jsonObject.getString("??"); // what to put here (??) as
//there is just a single word.
It may be very easy to get it but I feels I am missing something. Thanks for your help in advance.
URL just gives a word like - done that's it not even " or : { nothing
Then simply use the String variable s , don't convert it into json
plus you can put this JSONObject jsonObject = new JSONObject(s); in try-catch to recognize that respose is simply a valid json or not , if not it will throw an exception
try{
// exception will be thrown in case of invalid json
JSONObject jsonObject = new JSONObject(s);
}
catch(JSONException e){
// s containing a single word so use it as it is
}

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.

Get JSONObject by ID from another JSONObject - Android

I have a little issue with parsing JSON String which I get from a web server. So my JSON looks something like this :
{
..........
"statistics":{
"660":{
"param_id":660,
"cat_id":2,
"param_title":"Number",
"param_value":"26",
"value_type":"singleline",
"elem_order":"1"}
,
"662":{
"param_id":662,
"cat_id":2,
"param_title":"Name",
"param_value":"Dani",
"value_type":"singleline",
"elem_order":"2"
}
// --||--
}
}
So I get a JSONObject statisics and I want to get JSONObjects from statistics, but the problem is that their name is different everytime.So I can't just do json.getJSONObject("660");. So any suggestions how can I do that?
You can do something like this :
if(jsonObj.has("statistics")){
Iterator<Object> keys = stats.keys();
while(keys.hasNext()){
String key = (String) keys.next();
JSONObject obj = new JSONObject();
obj = stats.getJSONObject(key);
// get JSON
}// end while
}//end if
use JSONObject.keys() to get key iterator, then getJsonObject( key) to get object.
Try below code-
JSONArray nameArray = statisics.names();
JSONArray valArray = statisics.toJSONArray(nameArray);
where names() method returns array of names and it is stored in nameArray and valArray contains array of values corresponding to valArray.
You can iterate using for loop over these array to get values.
use like this
JSONObject jsonOnb = json.getJSONObject("statistics") ;
JSONObject pagesObj = jsonOnb.getJSONObject(jsonOnb.names().getString(0));
Log.i("pageid", "pageid= " +pagesObj.get("param_id"));
Log.i("title", "title= " +pagesObj.get("cat_id"));
..............

Categories

Resources