Android: Json get inner object - android

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

Related

JSONObject.toString() converts internal JSONArray as string in Android

I am creating a JSON request as followed:
JSONObject request = new JSONObject();
request.put("ID", "35");
request.put("password", "password");
List<JSONObject> fieldList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
fieldList.add(new JSONObject()
.put("unitid", "unitid " + i)
.put("price", "Price " + i));
}
request.put("unitsummary", new JSONObject()
.put("unitsummarydetail", fieldList)
);
String requestString = request.toString();
The value of requestString variable should be :
{
"ID": "35",
"password": "password",
"unitsummary": {
"unitsummarydetail": [
{
"price": "Price 0",
"unitid": "unitid 0"
},
{
"price": "Price 1",
"unitid": "unitid 1"
},
{
"price": "Price 2",
"unitid": "unitid 2"
}
]
}
}
But it is :
{
"ID": "35",
"password": "password",
"unitsummary": {
"unitsummarydetail": "[{\"unitid\":\"unitid 0\",\"price\":\"Price 0\"}, {\"unitid\":\"unitid 1\",\"price\":\"Price 1\"}, {\"unitid\":\"unitid 2\",\"price\":\"Price 2\"}]"
}
}
It is converting the unitsummarydetail as string.
I have tried but didn't find similar issue or any solution on internet.
Is there any issue in my code or this is the behavior of library?
Any ideas or solution code snippets are welcome.
Thanks.
Use JSONArray instead of ArrayList.
JSONObject request = new JSONObject();
request.put("ID", "35");
request.put("password", "password");
JSONArray fieldList = new JSONArray();
for (int i = 0; i < 3; i++) {
fieldList.put(new JSONObject() .put("unitid", "unitid " + i) .put("price", "Price " + i));
}
request.put("unitsummary", new JSONObject() .put("unitsummarydetail", fieldList) );
String requestString = request.toString();
Output:
{"ID":"35","password":"password","unitsummary":{"unitsummarydetail":[{"unitid":"unitid
0","price":"Price 0"},{"unitid":"unitid 1","price":"Price
1"},{"unitid":"unitid 2","price":"Price 2"}]}}
change your code
from
request.put("unitsummary", new JSONObject()
.put("unitsummarydetail", fieldList));
to
request.put("unitsummary", new JSONObject()
.put("unitsummarydetail", new JSONArray(fieldList)));
Crazy !!!!
JsonArray treatIdArray = new JsonArray(); // this one will result string : "["id", "id"]"
JSONArray treatIdArray = new JSONArray(); // this one will result array : ["id", "id"]
They are 2 different Json, lol, com.google.gson.JsonArray vs org.json.JSONArray and it took me almost a day. Oh my God !!!!
you could create a JSON array unitsummarydetail and add all the json objects unitsummary in a for loop

How can I parse string from PHP on ANDROID if my string has no starting value?

Let's assume that I have a string from the PHP request like this.
[
{
"id": "1",
"title": "\"Shaira Casandra Libao, the new PSSC President!\"",
"content": "\"Leadership is the key of success\" - Ms. Libao said.\n\nShaira Casandra Libao won the 75% of the vote. ", "penname": "John Ranniel A. Sinel", "date_send": "2015-01-02",
"sender": "John Ranniel Almendares Sinel",
"shortdesc": "The new PSSC President",
"lang": null
}
,
{
"id": "2",
"title": "\"Merleen Mercolita is now the new leader of LGBT community\"",
"content": "\"Being gay is not bad, it's just on man's judgmental mind..\" Ms. Mercolita said during her presscon wherein she admitted that she is a transwomen.",
"penname": "Shaira Casandra Libao",
"date_send": "2015-02-04",
"sender": "Shaira Boncato Libao",
"shortdesc": "LGBT on the go",
"lang": null
}
]
And I want to display only the title key of the first article on the string.
My code in android is:
//The string result variable is the value given by the onPostExecute() method
String title = "";
JSONObject jsonRootObj = new JSONObject(result);
JSONArray jsonArray = jsonRootObj.optJSONArray(whatamIgannaputOnIt);
JSONObject jsonObject = jsonArray.getJSONObject(0);
title = jsonObject.getString("title");
this.kemb.setText(title);
If I have a string like this:
{
"Data":
[
{
"id": "1",
"title": "\"Shaira Casandra Libao, the new PSSC President!\"",
"content": "\"Leadership is the key of success\" - Ms. Libao said.\n\nShaira Casandra Libao won the 75% of the vote. ", "penname": "John Ranniel A. Sinel", "date_send": "2015-01-02",
"sender": "John Ranniel Almendares Sinel",
"shortdesc": "The new PSSC President",
"lang": null
}
,
{
"id": "2",
"title": "\"Merleen Mercolita is now the new leader of LGBT community\"",
"content": "\"Being gay is not bad, it's just on man's judgmental mind..\" Ms. Mercolita said during her presscon wherein she admitted that she is a transwomen.",
"penname": "Shaira Casandra Libao",
"date_send": "2015-02-04",
"sender": "Shaira Boncato Libao",
"shortdesc": "LGBT on the go",
"lang": null
}
]
}
I can supply the JSONArray jsonArray = jsonRootObj.optJSONArray(whatamIgannaputOnIt); whatamIgannaputOnIt variable the string "Data" but on my case, I don't have that! What I have is the string on the top most of my question. So how can I get the correct output with that kind of string?
First, provided JSON String is JSONArray of JSONObject's
So, instead of getting JSONObject from string get JSONArray :
JSONArray jsonRootObj = new JSONArray(result);
Because jsonRootObj JSONArray contains only single JSONObject which is at 0 index, so use 0 to get JSONObject:
JSONObject jsonObj = jsonRootObj.getJSONObject(0);
String title = jsonObj.optString("title");
if jsonRootObj JSONArray contains more then one JSONObject then iterate over jsonRootObj to get title from all JSONObject's
I'm not sure I understand your question but you should do
JSONArray jsonArray = new JSONArray(result);
for(int i=0; i<jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString("title");
}

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

Parse JSON object from URL

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

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

Categories

Resources