How to get json array data without key name - android

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

Related

Can't access some member of JSON array Android

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

how can i parse JSON response

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/

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
}

Having trouble accessing object in JSON

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

how to parse a JSON data in side a table layout dynamically?In Android from a URL

I am Parsing a a JSON data from a URL..
I followed this tutorial to parse the dynamic JSON data
now am parsing the data,.
in a List view.. when I click on that list view a New Item view will appear in that I want to add some contents which are form a JSON data.. But its viewing the last one of the data So I parse it with a string format but I am getting the data in string but I want that data in a table..
this is my JSON data{
"request": "ok",
"query": {
"result": [
{
"details": [
{
"offers": [
{
"id": "UUkY8",
"model": "XL"
},
{
"id": "UUkY8",
"model": "XXL"
}
],
"count": 2,
"url": "http://www.wallmart.com"
},
{
"offers": [
{
"id": "NNkz4",
"model": "XL"
},
{
"id": "NNkz4",
"model": "XXL"
}
],
"count": 2,
"url": "http://www.amazon.com"
}
],
"flag": [
"http://www.donkersct.nl/wordpress/wp-content/uploads/2012/07/stackoverflow.png"
]
}
]
}
}
and I am parsing that in this way
JSONArray json_results_details =c.getJSONArray("details");
System.out.println("looping json_results_details");
String strOffermodel="";
for (int j = 0; j < c.length(); j++) {
System.out.println("looping json_results_details[" + j +"]" + "json_results_details.length() -->" + json_results_details.length());
if (j < json_results_details.length()) {
JSONObject d = json_results_details.getJSONObject(j);
stridsName += d.optString("name")+",";
stridsURLs += d.optString("url")+",";
// Get site details
long lOffer_Counts =-1;
try {
lOffer_Counts= Long.parseLong(d.optString("offers_count"));
} catch(Exception e) {
lOffer_Counts =-1;
}
strOffersCount+= String.valueOf(lOffer_Counts) + ",";
if(lOffer_Counts > 0) {
JSONArray json_offers = d.getJSONArray("offers");
System.out.println(json_offers.toString());
String strmodel="";
for (int k = 0; k < json_offers.length(); k++) {
JSONObject e = json_offers.getJSONObject(k);
map.put("id", e.optString("id"));
map.put("model", e.optString("model"));
strmodel += e.optString("model") + "$";
}
strOffermodel += strmodel + ",";
}
else
{
strOffermodel += ",";
}
map.put("id", stridsName);
map.put("model", strOffermodel);
}
}
arraylist.add(map);
So no I am getting the Model in loop.
as Model:XL,XXL/XL,XXL...
I tried with list view but failed now I am trying with table View..
But I want the output should be as
Here Only one id is showing I want all ID and all Model as a comperation..
Please help me to find out I am using a table inside a listviw, I tried with Listview inside a Listview.. But not worked..
I tried with increment the data means ID/Model with for loop as i+1 But its incrementing the value
means I am expected as
map.put("id", strOfferid);
map.put("id1", strOfferid1);
map.put("id2", strOfferid2);
map.put("id3", strOfferid3);
But I am incrementing the value like
Model:XL1,XXL1/XL2,XXL2/XL3,XXL3
So any one please help Regarding this..
use instead of
JSONObject d = json_results_details.getJSONObject(j);
this
JSONObject d = new JSONbject(json_results_details.getJSONObject(j));

Categories

Resources