I have JSON response and it have JSON array inside JSON array. Please tell me how to parse it. and please tell me it's best example for multiple JSON array parsing. I have all field dynamic so developer give me this kind of response. Thanks in advance.
{
"products": [
{
"id": "14",
"cat_id": [
"1"
],
"category_name": [
"Meetha Paan Sall Supari"
],
"name": "Chocco Paan",
"product_image": "http://freedemo.info/paanvaala/php/media/product_image/t0xdfosjr_1_173_201.png",
"price_unit": "in_pcs",
"price_id": [
"14"
],
"weight": [
"1 PCS"
],
"price": [
150
],
"mrp": [
"150.00"
],
"description": null
},
{
"id": "13",
"cat_id": [
"1"
],
"category_name": [
"Meetha Paan Sall Supari"
],
"name": "Chochobar Pan",
"product_image": "http://freedemo.info/paanvaala/php/media/product_image/hul6e69n6_1_173_201.png",
"price_unit": "in_pcs",
"price_id": [
"13"
],
"weight": [
"1 PCS"
],
"price": [
85
],
"mrp": [
"85.00"
],
"description": null
},
],
}
How to Parse JSON and what its has in it Follow here.
parse json:
JSONObject jsonObj = new JSONObject(jsonStr);// your string.
JSONArray jsonArray = jsonObj.getJSONArray("products");
for(int i=0; i < jsonArray.length(); i++){
JSONObject prod = jsonArray.getJSONObject(i);
String id = prod.getString("id");
// and so on ...you can parse the entire json using either array or object
}
surround with try catch for exception....
First you need to verif y if your JSON is valid or not.
Json Validator
if you find this valid then `
try { JSONObject jsonRootObject = new JSONObject(strJson);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonRootObject.optJSONArray("products");
//Iterate the jsonArray and print the info of JSONObjects
for(int i=0; i < jsonArray.length(); i++){
JSONObject jsonObject = jsonArray.getJSONObject(i);
int id = Integer.parseInt(jsonObject.optString("id").toString());
String name = jsonObject.optString("name").toString();
float product_image = Float.parseFloat(jsonObject.optString("product_image").toString());
JSONArray cat_idArray = jsonRootObject.optJSONArray("cat_id");
for(int i=0; i < cat_idArray.length(); i++){
//Here you can get other values
}
data += "Node"+i+" : \n id= "+ id +" \n Name= "+ name +" \n Salary= "+ salary +" \n ";
}
output.setText(data);
} catch (JSONException e) {e.printStackTrace();}
`
Also there are lots of example in web where you can learn.
like this one
Json parsing is all about understanding the hierarchy of objects '{}' and array '[]' . you can look at following links to understand it.
How to parse this nested JSON array in android
or http://www.coderzheaven.com/2011/06/10/complex-json-string-parsing-in-android/
Related
This is my json data i want to get the first_movie name in top headder and rest of data under that and same as well other work also
{
"actors": [
{
"name": "Amitabh Bachchan",
"age": 76,
"bollywood": true,
"img": "https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Amitabh_Bachchan_2014.jpg/220px-Amitabh_Bachchan_2014.jpg",
"notablework": [
{
"first_movie": "Saat Hindustani"
},
"Anand(1971)",
"Zanjeer(1973)",
"Sholay(1975)",
"Don(1978)",
"Agneepath(1990)",
"Black(2005)",
"Paa(2009)",
"Piku(2016)"
],
"other_work": [
"Politics",
"Television appearances",
"Voice-acting",
"Humanitarian causes",
"Business investments"
]
},
{
"name": "Salman Khan",
"age": 53,
"bollywood": true,
"img": "https://upload.wikimedia.org/wikipedia/commons/thumb/8/86/Salman_Khan_at_Renault_Star_Guild_Awards.jpg/220px-Salman_Khan_at_Renault_Star_Guild_Awards.jpg",
"notablework": [
{
"first_movie": "Biwi Ho To Aisi"
},
" Biwi Ho To Aisi (1988)",
"Maine Pyar Kiya (1989)",
" Hum Aapke Hain Koun..! (1994)",
" Karan Arjun (1995)"
],
"other_work": [
"Television",
"Brand endorsements"
]
},click here to view my design that i want to show this data
I think you shared two json objects Only as i understand.
Your JSON
{
"actors":[
{
"name":"Amitabh Bachchan",
"age":76,
"bollywood":true,
"img":"https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Amitabh_Bachchan_2014.jpg/220px-Amitabh_Bachchan_2014.jpg",
"notablework":[
{
"first_movie":"Saat Hindustani"
},
"Anand(1971)",
"Zanjeer(1973)",
"Sholay(1975)",
"Don(1978)",
"Agneepath(1990)",
"Black(2005)",
"Paa(2009)",
"Piku(2016)"
],
"other_work":[
"Politics",
"Television appearances",
"Voice-acting",
"Humanitarian causes",
"Business investments"
]
},
{
"name":"Salman Khan",
"age":53,
"bollywood":true,
"img":"https://upload.wikimedia.org/wikipedia/commons/thumb/8/86/Salman_Khan_at_Renault_Star_Guild_Awards.jpg/220px-Salman_Khan_at_Renault_Star_Guild_Awards.jpg",
"notablework":[
{
"first_movie":"Biwi Ho To Aisi"
},
" Biwi Ho To Aisi (1988)",
"Maine Pyar Kiya (1989)",
" Hum Aapke Hain Koun..! (1994)",
" Karan Arjun (1995)"
],
"other_work":[
"Television",
"Brand endorsements"
]
}
]
}
Here we process the above data
JSONObject json_obj = new JSONObject(response);
//we have the array named hero inside the object
//so here we are getting that json array
JSONArray actorsArray = json_obj.getJSONArray("actors");
//now looping through all the elements of the json array
for (int i = 0; i < actorsArray.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject actorsObject = actorsArray.getJSONObject(i);
String actorsName = actorsObject.getString("name");
//Here you can get same like your remaining string data by using json key -> age,bollywood,img
//now we can process notablework object
JSONArray notableworkArray = actorsObject.getJSONArray("notablework");
// now we need another loop for get notable data
for (int j = 0; j < notableworkArray.length(); j++) {
if(j==0) {
JSONObject notableworObject = notableworkArray.getJSONObject(0);
String first_movie = notableworObject.getString("first_movie");
}
}
}
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
}
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
I am trying to access the "display_name" object within the following JSON and I cannot seem to grab it. The example JSON is below.
{
"streams": [
{
"broadcaster": "fme",
"_id": 5019229776,
"preview": "http://static-cdn.jtvnw.net/previews-ttv/live_user_zisss-320x200.jpg",
"game": "Diablo III",
"channel": {
"mature": null,
"background": "http://static-cdn.jtvnw.net/jtv_user_pictures/zisss-channel_background_image-06a9d8c1113e5b45.jpeg",
"updated_at": "2013-03-04T05:27:27Z",
"_id": 31795858,
"status": "Barb sets giveaway and making 500m DH set... Join Zisspire, earn Zeny, collect prizes!",
"logo": "http://static-cdn.jtvnw.net/jtv_user_pictures/zisss-profile_image-502d7c865c5e3a54-300x300.jpeg",
"teams": [ ],
"url": "http://www.twitch.tv/zisss",
"display_name": "Zisss",
"game": "Diablo III",
"banner": "http://static-cdn.jtvnw.net/jtv_user_pictures/zisss-channel_header_image-997348d7f0658115-640x125.jpeg",
"name": "zisss",
"video_banner": null,
"_links": {
"chat": "https://api.twitch.tv/kraken/chat/zisss",
"subscriptions": "https://api.twitch.tv/kraken/channels/zisss/subscriptions",
"features": "https://api.twitch.tv/kraken/channels/zisss/features",
"commercial": "https://api.twitch.tv/kraken/channels/zisss/commercial",
"stream_key": "https://api.twitch.tv/kraken/channels/zisss/stream_key",
"editors": "https://api.twitch.tv/kraken/channels/zisss/editors",
"videos": "https://api.twitch.tv/kraken/channels/zisss/videos",
"self": "https://api.twitch.tv/kraken/channels/zisss",
"follows": "https://api.twitch.tv/kraken/channels/zisss/follows"
},
"created_at": "2012-07-01T21:09:58Z"
},
"name": "live_user_zisss",
"viewers": 775,
"_links": {
"self": "https://api.twitch.tv/kraken/streams/zisss"
}
}
],
"_links": {
"summary": "https://api.twitch.tv/kraken/streams/summary",
"followed": "https://api.twitch.tv/kraken/streams/followed",
"next": "https://api.twitch.tv/kraken/streams?channel=zisss%2Cvoyboy&game=Diablo+III&limit=100&offset=100",
"featured": "https://api.twitch.tv/kraken/streams/featured",
"self": "https://api.twitch.tv/kraken/streams?channel=zisss%2Cvoyboy&game=Diablo+III&limit=100&offset=0"
}
I start with:
JSONArray array = getJSONArray("streams");
JSONObject object = array.getJSONObject(4); // channel is entry 4 in array
String name = object.getString("display_name");
I'm not sure what I'm doing wrong here. With a more filled out JSON with multiple "channel" entries, I'm not sure how to handle it. I was thinking something like this?
String[] name = new String[array.length()];
JSONArray array = getJSONArray("streams");
for(int i = 0; i < array.length(); i++) {
if(array[i].equals("channel")
name[i] = array.getString("display_name");
I'm sure that last part is crude, and probably quite off from what it should be, but I'm not sure how to handle this.
Based on your JSON you have to do the following
JSONArray array = getJSONArray("streams");
JSONObject object = array.getJSONObject(0);
object = object.getJSONOBject("channel")
String name = object.getString("display_name");
The first item in you json array holds the channel object which contains the data you are looking for.
Channel is not the 4th item in your JSONArray but a nested object within the first. You have to be careful to follow the [] and {} brackets when parsing JSON because JSONObjects can contain multiple nested sub-objects and arrays.
JSONObject mainJsonObject = new JSONObject(json_string);
JSONArray array = mainJsonObject.getJSONArray("streams");
JSONObject channelObject = array.getJSONObject(0).getJSONOBject("channel")
String displayName = channelObject.getString("display_name");