Parse json array in Response - android

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");
}

Related

how to parse this JSONArray

Hi guys i have this JSONObject I'm having hard time to parse it.
Here's the JSON,
{
"query": {
"count": 2,
"created": "2016-11-07T15:29:47Z",
"lang": "en-US",
"results": {
"rate": [{
"id": "USDINR",
"Name": "USD/INR",
"Rate": "66.7700",
"Date": "11/7/2016",
"Time": "3:27pm",
"Ask": "66.8000",
"Bid": "66.7700"
}, {
"id": "USDEUR",
"Name": "USD/EUR",
"Rate": "0.9060",
"Date": "11/7/2016",
"Time": "3:29pm",
"Ask": "0.9065",
"Bid": "0.9060"
}]
}
}
}
As you can see above there are two "Rate" I want to store first "Rate" to a String array called Result[0] and second "Rate" to Result[1].
Here what I'm trying.
JSONObject object = new JSONObject(JSON);
JSONObject rateObject = object.getJSONObject("rate");
JSONArray rateArray = rateObject.getJSONArray("Rate");
result[0] = rateArray.getString(0);
result[1] = rateArray.getString(1);
I know maybe I'm doing this like stupid. So please help me out.
To Get the array I would try this:
JSONObject object = new JSONObject(JSON);
JSONObject rateObject = object.getJSONObject("results");
JSONArray rateArray = rateObject.getJSONArray("rate");
And then use a for to read all objects in the array:
int length = rateArray.length();
for (int i =0; i < length; i++){
JSONObject rate = rateArray.getJSONObject(i);
String rateResult = rate.getString("Rate");
}
Your formatted JSON looks like this
{
"query":{
"count":2,
"created":"2016-11-07T15:29:47Z",
"lang":"en-US",
"results":{
"rate":[
{
"id":"USDINR",
"Name":"USD/INR",
"Rate":"66.7700",
"Date":"11/7/2016",
"Time":"3:27pm",
"Ask":"66.8000",
"Bid":"66.7700"
},
{
"id":"USDEUR",
"Name":"USD/EUR",
"Rate":"0.9060",
"Date":"11/7/2016",
"Time":"3:29pm",
"Ask":"0.9065",
"Bid":"0.9060"
}
]
}
}
}
To get the rate array you have to this
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray rateArray = jsonObject.getJSONObject("query").getJSONObject("results").getJSONArray("rate");
Then query rate array like this
JSONObject rateJSON = (JSONObject)rateArray.get(index);
String id = rateJSON.getString("id"); //Or any other field of rate
Anthony,
You need to go from the root element ( query ) to the "rate" node :
JSONArray rates = object.getJSONObject("query").getJSONObject("results").getJSONArray("rate")
result[0] = rates.getJSONObject(0).get("Rate")
result[1] = rates.getJSONObject(1).get("Rate")
you need to do this
JSONObject jsonObj = new JSONObject(jsonString);
JSONObject queryObj = jsonObj.getJSONObject("query");
JSONObject resultObj = queryObj.getJSONObject("results");
JSONArray rateArr = resultObj.getJSONArray("rate");
result[0] = rateArr.getJSONObject(0).getString("Rate");
result[1] = rateArr.getJSONObject(1).getString("Rate");
Try this:
JSONArray rateArray = new JSONObject(JSON)
.getJSONObject("query")
.getJSONObject("results")
.getJSONArray("rate");
result[0] = rateArray.getJSONObject(0).getString("Rate");
result[1] = rateArray.getJSONObject(1).getString("Rate");

Retrieve Array value from JSOn to android client Array

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. :)

JSON with different structure - Android

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));
}

How to retrieve data using json parsing when there are multiple inner nodes?

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
}

Fetch value from JSON in android

I am sending request to the server and it gives me a response and giving data in JSON formats, now i want to fetch some specific value from that JSON format, so hot to do it.
{
"education": [
{
"school": {
"id": "2009305",
"name": "FG boys public high school Bannu Cantt "
},
"type": "High School"
},
{
"school": {
"id": "109989",
"name": "University of Engineering & Technology"
},
"type": "College"
}
],
"id": "xxxxxxx"
}
Now i need the school names from this xml,
Try this..
You response is in Json format not xml.
JSONObject json = new JSONObject(response);
JSONArray education = json.getJSONArray("education");
for(int i = 0; i < education.length(); i++){
JSONObject con_json = education.getJSONObject(i);
String school_type = con_json.getString("type");
JSONObject school_json = con_json.getJSONObject("school");
String school_name = school_json.getString("name");
}
It is not XML. it is completely in Json Standard format.
first build a JSONobject from your data:
JSONObject jsonObj = new JSONObject(result); //result = your Data String in fetched from server
then you cab retrieve what you want using its key. for example:
jsonObj.getString("id"); // it returns "xxxxxxx". as is in your data

Categories

Resources