Parse JSON object from URL - android

Im newbie in using JSON
{
"orders": [
{
"id": "12",
"ord_name": "Passion Fruit",
"ord_desc": "Cold passion fruit",
"ord_price": "75",
"ord_qty": "3",
"customer_id": "54feec24bff73",
"ord_num": "13191554feec24bff73",
"price_x_quan": "225.00",
"image": "http:\/\/192.168.43.52\/MMOS\/uploads\/passion-fruit.jpg",
"subtotal": "",
"imgimg": "uploads\/passion-fruit.jpg"
},
{
"id": "13",
"ord_name": "Caramel Mocha",
"ord_desc": "Cold caramel mocha",
"ord_price": "100",
"ord_qty": "1",
"customer_id": "54feec24bff73",
"ord_num": "13191554feec24bff73",
"price_x_quan": "100.00",
"image": "http:\/\/192.168.43.52\/MMOS\/uploads\/caramelmocha.jpg",
"subtotal": "",
"imgimg": "uploads\/caramelmocha.jpg"
}
],
"o_total": 325
}
'Im done parsing the array orders.
What I want now is to parse the o_total and put it on a TextView .
Any idea how to do this?
This is how i did in the first array = 'orders'
which is displayed on a listview
try {
// Locate the array name in JSON==
jsonarray = jsonobject.getJSONArray("orders");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("id", jsonobject.getString("id"));
map.put("ord_name", jsonobject.getString("ord_name"));
map.put("ord_price", jsonobject.getString("ord_price"));
map.put("ord_qty", jsonobject.getString("ord_qty"));
map.put("customer_id", jsonobject.getString("customer_id"));
map.put("ord_num", jsonobject.getString("ord_num"));
map.put("price_x_quan", jsonobject.getString("price_x_quan"));
map.put("image", jsonobject.getString("image"));
map.put("text_ordernumber",home_in.getStringExtra("text_ordernumber"));
map.put("text_name",home_in.getStringExtra("text_name"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
i wonder how to do it on "o_total"

I suppose you did something like this to get your array:
JSONObject rootObject = new JSONObject(yourJSONString);
rootObject.getJSONArray("order");
Just do the same to your "o_total":
yourTextView.setText(rootObject.getString("o_total"));

Just do:
int o_total = jsonobject.get("o_total").getAsInt();

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 to parse Double array JSON

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

Parsing JSON response without an array name

[
{
"stDescription": "END N/A",
"stCategory": "6",
"sZone": "#",
"sIncident": "0"
},
{
"stDescription": "BEG N/A",
"stCategory": "6",
"sZone": "#",
"sIncident": "0"
},
{
"stDescription": "",
"stCategory": "Null",
"sZone": "4",
"sIncident": "0"
},
{
"stDescription": "",
"stCategory": "Null",
"sZone": "5",
"sIncident": "0"
}
]
There is no array name here, but I want to parse whole array (my JSON parser works fine if I'm using array name).
For parsing this type of JSON...
First store it in String..
and then do following process...
String str = "JSON STRING";
JSONArray jsonarray = new JSONArray(str);
for(int i=0; i<jsonarray.length(); i++){
JSONObject obj = jsonarray.getJSONObject(i);
String stDescription = obj.getString("stDescription");
String stCategory= obj.getString("stCategory");
//and other fields
System.out.println(stDescription);
System.out.println(stCategory);
}
This may help you...

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
}

Android: Json get inner object

I'm trying to get the inner object of a json array (my jargon could be incorrect) that looks like this:
{
"News": {
"0": {
"name": "nytimes",
"fullName": "The New York Times",
"text": "#OwenPerry We heard from the owner of the house and corrected the article http://t.co/8GEgGy7",
"timestamp": "2011-08-15 12:20:36"
},
"1": {
"name": "HuffingtonPost",
"fullName": "Huffington Post",
"text": "Look out! New Zealand Skier chased by angry bulls - http://t.co/L0PZkx4",
"timestamp": "2011-08-15 12:19:04"
}
}
}
My code to retrieve the inner objects looks like this:
JSONArray category = json.getJSONArray("News");
JSONArray innerobj = category.getJSONArray(0);
for (int i = 0; i < innerobj.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = innerobj.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name", c.getString("fullName") + "\n(#"
+ c.getString("name") + ") ");
map.put("text",
c.getString("text") + "\n - "
+ c.getString("timestamp"));
mylist.add(map);
}
Any Ideas on what i'm doing incorrectly?
You don't have JSONArray, but JSONObjects. Your JSONObject structure is:
Main JSONObject, which contains 1 JSONObject - "news"
"news" contains two JSONObjects, "0" and "1"
Each of those objects have four fields - "name", "fullname", "text" and "timestamp"
Consider:
JSONObject jobj = new JSONObject(yourString);
JSONObject newsobj = jobj.getJSONObject("news");
JSONObject firstOne = newsobj.getJSONObject("0"); // this is the object "0"
....

Categories

Resources