I'm getting JSON with different structure. One is with gallery, but other not.
First JSON: (without gallery)
{
"id": "12345",
"title": "titletitle",
"fulltext": "texttext",
"related_articles":[
{
"id": "12346",
"title": "titletitle",
"image_name": "www.example.com/img1.png"
},
{
"id": "12347",
"title": "titletitle",
"image_name": "www.example.com/img2.png"
}
]
}
Second JSON (with gallery)
{
"id": "12345",
"title": "titletitle",
"fulltext": "texttext",
"gallery": [
"www.example.com/img1.png",
"www.example.com/img1.png",
"www.example.com/img1.png",
"www.example.com/img1.pngg",
"www.example.com/img1.png"
],
"related_articles":[
{
"id": "12346",
"title": "titletitle",
"image_name": "www.example.com/img1.png"
},
{
"id": "12347",
"title": "titletitle",
"image_name": "www.example.com/img2.png"
}
]
}
I'm putting this JSON into array like this:
data = whole JSON file, which I get from web service
JSONObject jRealObject = new JSONObject(data);
title = jRealObject.getString("title").toString();
text = jRealObject.getString("fulltext").toString();
JSONArray jArray = jRealObject.getJSONArray("gallery");
for (int i = 0; i < jArray.length(); i++) {
gallery.add(jArray.getString(i));
}
JSONArray jArray = jRealObject.getJSONArray("related_articles");
for (int i = 0; i < jArray.length(); i++) {
jRealObject = jArray.getJSONObject(i);
relatedId[i] = jRealObject.getString("id").toString();
relatedTitle[i] = jRealObject.getString("title").toString();
relatedImage[i] = jRealObject.getString("image_name").toString();
}
So when I get JSON with gallery it works perfect, but when article don't have gallery, I get exception:
W/System.err(30635): org.json.JSONException: No value for gallery
How can I check, if there is "gallery" in JSON ??
You can use the GSON library, this library is a json parse to objects and is very powerfull.
Here You have example for you can implemented this library with you json response.
Tutorial-Android-Parsing-JSON-with-GSON
GSON tutorial
JSONArray jArray = jRealObject.optJSONArray("gallery",null);
if(jArray != null)
for (int i = 0; i < jArray.length(); i++) {
gallery.add(jArray.getString(i));
}
Related
I have been trying to extract array elements from my JSON, but unable to, so far.
I have the following JSON:
{
"Sample JSON": [{
"Title": "Title1",
"Audit": [{
"auditId": "01",
"type": "sampleType",
"auditText": "sampleText",
"answer": ["Ans1", "Ans2"]
},
{
"auditId": "02",
"type": "sampleType2",
"auditText": "sampleText2",
"answer": ["Ans1", "Ans2", "Ans3", "Ans4"]
}
]
},
{
"Title": "Title2",
"Audit": [{
"auditId": "03",
"type": "sampleType3",
"auditText": "sampleText3",
"answer": ["Ans1", "Ans2"]
},
{
"auditId": "04",
"type": "sampleType4",
"auditText": "sampleText4",
"answer": ["Ans1", "Ans2", "Ans3", "Ans4"]
}
]
}
]
}
I want to extract the array elements of the array 'answer'.
I get exception in the line indicated in comment in the method below:
public void getAudit(String myJSON) {
auditList = new ArrayList<AuditList>();
String title;
String auditId;
String type;
String auditText;
ArrayList<String> answer = new ArrayList<>();
try {
JSONObject jsonObj = new JSONObject(myJSON);
JSONArray jssArray = jsonObj.getJSONArray("Sample JSON");
int jsonArrLength = jssArray.length();
for (int i = 0; i < jsonArrLength; i++) {
JSONObject jsonChildObj = jssArray.getJSONObject(i);
title = jsonChildObj.getString("Title");
JSONArray jssArray1 = jsonChildObj.getJSONArray("Audit");
for (int i1 = 0; i1 < jssArray1.length(); i1++) {
JSONObject jsonChildObj1 = jssArray1.getJSONObject(i1);
type = jsonChildObj1.optString("type");
auditText = jsonChildObj1.optString("auditText");
auditId = jsonChildObj1.optString("auditId");
JSONArray jssArray2 = jsonChildObj1.getJSONArray("answer");
//Getting exception in above line
for (int j=0; j<jssArray2.length(); j++)
{
answer.add(jssArray2.get(j).toString()) ;
}
AuditList aList = new AuditList();
aList.setQuesId(auditId);
aList.setQuesText(auditText);
aList.setQuesTypw(auditType);
aList.setAnswer(answer);
aList.setCategoryName(title);
auditList.add(aList);
}
}
.
.
.
.
.
}
I found the exception occurring in the line indicated above using the debugger.
Couldn't find a way to extract array elements of the array 'answer'.
Please help.
if(!jsonChildObj1.get("answer").toString().equals("")){
JSONArray jssArray2 = jsonChildObj1.getJSONArray("answer");
for (int j=0; j<jssArray2.length(); j++)
{
answer.add(jssArray2.get(j).toString()) ;
}
}
The exception that occurred to you because of Empty Data (""). To Prevent this validate it and getJSONArray(). refer
The way I do this kind of stuff is by going to this link and then paste my json there and get my class. After that, you can go and add Gson to your gradle by adding this line to your build.gradle:
compile 'com.google.code.gson:gson:2.6.2'
Then just create an instance of the created class that you just created and convert json into your target class:
NewClass classObject = new Gson().fromJson(YOUR_JSON, NewClass.class);
I have JSON array like this
[
{
"ride_id": "48",
"user_id": "22",
"event_id": "42",
"driver_id": "0",
"pick_up_location": "11111"
},
{
"ride_id": "48",
"user_id": "21",
"event_id": "42",
"driver_id": "0",
"pick_up_location": "11111"
},
{
"name": "ofir rosner",
"image": "",
"address": "Yokne\\'am Illit, Israel"
},
{
"name": "hhhh",
"image": "profilePictureOfUserId22.JPG",
"address": "ffffd"
}
]
im using OKhttp3 to retrieve my data like
Response response = client.newCall(request).execute();
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
...........
but the object of JSONObeject in place i only contains
{"ride_id":"50","user_id":"2","event_id":"44","driver_id":"0","pick_up_location":"11111"}
but I want to be able to do something like this object.setString("name")
or to get to the object in the place i for name, image and address
Your all object don't have name key-value pair so you can use optString , It returns an empty string if there is no such key
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
String name = object.optString("name");
// optionally use object.optString("name","No Name Found");
// To display some default string as name
if(!name.isEmpty()){
// we got the data , use it
Log.i("name is ",name); // display data in logs
}
}
or you can use has which Determine if the JSONObject contains a specific key.
JSONArray array = new JSONArray(response.body().string());
for (int i=0; i<array.length(); i++){
JSONObject object = array.getJSONObject(i);
String name;
if(object.has("name")){
name = object.optString("name"); // got the data , use it
}
}
{ // this object has no "name" key-value pair and so does some other object
"ride_id": "48",
"user_id": "22",
"event_id": "42",
"driver_id": "0",
"pick_up_location": "11111"
}
I can't seem to understand how to parse the "dispay_sizes" JSON array.
Here is my approach so far.
This is the JSON
{
"result_count": 6577719,
"images": [
{
"id": "505093872",
"asset_family": "creative",
"caption": "Professional footballer kicking ball during game in floodlit soccer stadium full of spectators under stormy sky and floodlights. It's snowing up there.",
"collection_code": "EPL",
"collection_id": 712,
"collection_name": "E+",
"display_sizes":
[{
"is_watermarked": false,
"name": "thumb",
"uri": "http://cache4.asset-cache.net/xt/505093872.jpg?v=1&g=fs1|0|EPL|93|872&s=1&b=RjI4"
}],
"license_model": "royaltyfree",
"max_dimensions": {
"height": 6888,
"width": 8918
},
"title": "Soccer player kicking a ball"
},
My code to parse it:
JSONObject imageData = new JSONObject(jsonData);
int resultCount = imageData.optInt("result_count");
Log.d("Result Count: ",Integer.toString(resultCount));
JSONArray imageArray = imageData.optJSONArray("images");
for( int i = 0; i < imageArray.length(); i++)
{
JSONObject img= imageArray.getJSONObject(i);
String id = img.optString("id");
allID.add(id);
Log.d("Image ID: ", id);
JSONArray imagePath = img.getJSONArray("display_sizes");
String pathURI = imagePath.getString("uri");
Log.d("Image Path: ",pathURI);
}
Can someone explain how to parse JSON array within a JSON array?
This
JSONArray imagePath = img.getJSONArray("display_sizes");
is right
[ // represents json array
{ // jsonobject
"is_watermarked": false,
"name": "thumb",
"uri": "http://cache4.asset-cache.net/xt/505093872.jpg?v=1&g=fs1|0|EPL|93|872&s=1&b=RjI4"
you have array of json object.
So you need
for(int j=0;j<imagePath.length();j++)
{
JSONObject jb = imagePath.getJSONObject(j);
String pathURI = jb.getString("uri");
}
i am doing now retrieving JSON array and assigning it to Android Array String but it failed.
My integer "success" already well. Please help, thank you very much.
My JSON information:
{
"details": [
{
"phone": "89898999",
"name": "Maria"
},
{
"phone": "98983555",
"name": "John"
},
{
"phone": "96969677",
"name": "Leo"
},
{
"phone": "97320099",
"name": "Helen"
},
{
"phone": "90063379",
"name": "Judy"
}
],
"success": 1
}
Android code:
String[] titleArray2;
String[] descriptionArray2;
int cs = 0;
.....
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
cs = jsonObject.getInt("success")
JSONArray ja = jsonObject.getJSONArray("details");
for (int i = 0; i < ja.length(); i++)
{
JSONObject jo = (JSONObject) ja.get(i);
titleArray2[i] = jo.getString("phone");
descriptionArray2[i] = jo.getString("name");
}
Your code looks fine, Just try initializing your array
Try like this
JSONArray ja = jsonObject.getJSONArray("details");
titleArray2 =new String[ja.size];
descriptionArray2[i]=new String[ja.size];
and then your for loop.
Mark as right if it works for you. :)
I am trying to retrieve data using a URL using Json Parsing in Android.
I have done the following coding but I am not able to figure out how to parse the node which is present in the inner node items.
My json array and codes are posted as below. Please guide me step by step.
Part of the Json Array
[
{
"items": [
{
"id": "11",
"Item_Id": "123",
"Item_Name": "Chicken Cream Soup",
"Price": "8",
"Currency": "AED",
"Category": "Soup",
"Description": "Creamy Chicken Soup with garnish & side helpings",
"Unit": "2",
"food_type": "Non",
"Image_Large": "/images_large/chickensoup.jpg",
"Image_Thumb": "/images_large/chickensoup.jpg",
"Timestamp": "6/23/2014 9:49:43 PM",
"Promotion": "",
"Item_Name_arabic": "حساء الطماطم",
"Item_Name_russian": "",
"Currency_arabic": "درهم",
"Currency_russian": "",
"Description_arabic": "حساء الطماطم",
"Description_russian": "",
"Note": "",
"Nutritional_info": "",
"extrafield_1": "",
"extrafield_2": "",
"preferncess": [
"No Salt",
"Extra Sugar"
],
"preferncess_ids": [
"1",
"2"
],
"price": [
"4",
"5"
],
"preferncess_arabic": [
"لا الملح",
"سكر اضافية"
]
},
MainActivity.class
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
items = jsonObj.getJSONArray(TAG_CONTACTS);
Log.i("json node",""+items);
// looping through All Contacts
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
String id = c.getString("id");
//String name = c.getString(TAG_NAME);
Log.w("myid", id);
} catch (JSONException e) {
e.printStackTrace();
}
// fetch item array
JSONArray itemObjectArray = jsonStr.getJSONArray("items");
for (int i = 0; i < itemObjectArray.length(); i++) {
// fetch item object at i position
JSONObject itemObject = itemObjectArray.getJSONObject(i);
// fetch values from itemObject
String idValue = itemObject.getString("id");
String noteValue = itemObject.getString("Note");
// fetch the array
JSONArrayprefObject = itemObject.getJSONArray("preferncess");
// iterate throgh the array like
for (int i = 0; i < prefObject .length(); i++) {
JSONObject p = prefObject .getJSONObject(i);
}
}
preference is json array you can retrive it by c.getJSONArray("preferncess"); and then iterating. or in more generic you can Can you try something like following
if (c.get(key) instanceof String)
{
JSONObject Lawset = c.getString(key);
} else if (c.get(key) instanceof JSONObject)
{
JSONObject Lawset = c.getJSONObject(key);
//try to retrieve data from json object
}
else if (c.get(key) instanceof JSONArray)
{
JSONArray Lawset = c.getJSONArray(key);
//iterate to get data
}