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"
}
Related
I created an app that stream video from server, on server side (PHP) I use this code to pass the MySQL query result via JSON array contain a result of video title size and views.
$query="select * from video_tble ;";
$result=mysqli_query($con,$query);
$row=mysqli_fetch_all($result,MYSQLI_ASSOC);
$respones_result=array();
$response_result=$row;
echo json_encode(array("server_response_result"=>$response_result));
But I don't know how to retrieve a multidimensional array using JSON object.
JSONObject jsonObject1=new JSONObject(json);
JSONArray jsonArray1=jsonObject1.getJSONArray("server_response_result");
JSONObject JO1=jsonArray1.getJSONObject(0);
String [] title =...?
If it was a name value pair then I follow this strategy:
String title1=JO1.getString("title");
But I don't know what to do on multidimensional array.
Hi you need a for loop like this
for(int i;i<jsonArray1.size();i++){
JSONObject JO1=jsonArray1.getJSONObject(i);
String title1=JO1.getString("title");
}
To parse this json
{
"server_response_result": [{
"videoid": "1",
"videotitle": "Metro Shoes",
"userid": "7",
"category": "Fashion",
"dou": "0000-00-00",
"rate": "3",
"vstatus": "A",
"vcount": "321",
"location": "adstreamer\\uploads\\ramesh#gmail.com\\1.mp4"
}, {
"videoid": "2",
"videotitle": "Lijn the bus",
"userid": "7",
"category": "App",
"dou": "0000-00-00",
"rate": "4",
"vstatus": "A",
"vcount": "145",
"location": "adstreamer\\uploads\\ramesh#gmail.com\\2.mp4"
}]
}
You have to do following steps (saying you have the server response in jsonObject.
ArrayList<SomeModel> modelList = new ArrayList<>();
JSONArray serverResponseResult = jsonObject.getJsonArray("server_response_result");
for (int i = 0; i < serverResponseResult.length(); i++) {
JSONObject result = serverResponseResult.get(i);
String videoId = result.getString("videoid");
String videoTitle = result.getString("videotitle");
...
// instead of using String, set the values in the model class
modelList.add(/* model */);
}
In my application I'm trying to parse This structure type Json value. Did any of you guys face this issue? Any help would be greatly appreciated.
Main problem is double [[
[
[
{
"nid": "29",
"vid": "30",
"type": "oa_discussion_post",
"language": "und",
"title": "We want to hear from you.",
"uid": "1",
"status": "1",
"created": "1441316801",
"changed": "1442461699",
"comment": "2",
"promote": "0",
"sticky": "0",
"tnid": "0",
"translate": "0",
"uuid": "b9cb0351-5dbc-4ef1-8f8c-5570b66a2339"
}
]
]
Here is my approach:
JSONArray json = new JSONArray(jsonData);
for(int i=0;i<json.length();i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = json.getJSONObject(i);
String userType=e.getString("vid");
String topLine=e.getString("type");
}
Where is my error?
you have a nested array inside the top level array
for(int i=0;i<json.length();i++) {
JSONArray nestedJsonArray = json.optJSONArray(i);
if (nestedJsonArray != null) {
for(int j=0;j<nestedJsonArray.length();j++) {
// use j and nestedJsonArray to retrieve the JSONObect
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = nestedJsonArray.optJSONObject(i);
String userType=e.optString("vid");
String topLine=e.optString("type");
}
}
}
You have another JSONArraybut you use JSONObject. Just do
JSONArray firstArray = new JSONArray(jsonData);
JSONArray secondArray = firstArray.getJSONArray(0);
JSONObject jsonObject = secondArray.getJSONObject(0);
//Do want you want with your jsonObject
String userType = jsonObject .getString("vid");
String topLine = jsonObject .getString("type");
You have an object in an array in an array.
You have to select the first array in it instead of selecting the JSONObject directly. After selecting the second JSONArray, then select your JSONObject using getJSONObject(0);
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 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");