This question already has answers here:
How to call the JSON object in Android
(5 answers)
Closed 8 years ago.
i am trying to use one json file in my project.i have one Json file in following structure,i succeed to access json array "business", but now i want to access business_cat and in business_cat, cat 1 and cat 2. how can i access these values?
{
"business":[
{
"id":"13",
"category":"Dinner",
"subcategory":"",
"name_eng":"dinner 1",
"name_arab":"dinner 1",
"mobile":"12345",
"address":"not now",
"logo":"1.gif",
"contact":"Call",
"open_time":" ",
"close_time":" "
}
],
"business_cat":[
[
"cat 1",
{
"name":"dish 1",
"id":"7",
"name_arab":"dish1",
"price":"200",
"logo":"laptop.jpeg"
},
{
"name":"dish 2",
"id":"8",
"name_arab":"dish 2",
"price":"123789",
"logo":"micky.jpg"
},
{
"name":"qaz",
"id":"10",
"name_arab":"zaq",
"price":"12",
"logo":"watch.jpg"
},
{
"name":"wsx",
"id":"11",
"name_arab":"xsw",
"price":"12",
"logo":"micky.jpg"
},
{
"name":"zxc",
"id":"12",
"name_arab":"vcxz",
"price":"34",
"logo":"camera.jpg"
}
],
[
"cat2",
{
"name":"d1",
"id":"9",
"name_arab":"d1",
"price":"300",
"logo":"watch.jpg"
}
]
]
}
A JSON Object starts with a { and ends with a } while a JSON Array starts with a [ and ends with a ].
The whole string will be JSONObject, from which each array can be extracted via json.getJSONArray(ARRAYNAME)
JSONObject json = new JSONObject(jsonString);
JSONArray business = json.getJSONArray("business");
//business
System.out.println("*****business*****"+business.length());
for(int i=0;i<business.length();i++){
JSONObject json_data_business = business.getJSONObject(i);
Log.i("log","id"+json_data_business.getInt("id")+
", category"+json_data_business.getString("category")
);
// business_cat
JSONArray business_cat = json.getJSONArray("business_cat");
System.out.println("*****business_cat*****"+business_cat.length());
for(int i=0;i<business_cat.length();i++){
JSONObject json_data_business_cat = business_cat.getJSONObject(i);
Log.i("log","id"+json_data_business_cat.getInt("id")+
", name"+json_data_business_cat.getString("name")
);
}
JSONObject obj = new JSONObject(content);
if (obj != null) {
Iterator<?> it = obj.keys();
while (it.hasNext()) {
String key = it.next().toString();
JSONArray value = (JSONArray) obj.optString(key);
---then you parse the JSONArray
}
}
Related
i am converting a xml content into JSON content and the content is as follows
{
"response":
{
"seatlist":
{
"seat":
{
"balance":85694.6,"num":12
},
"seat":
{
"balance":85694.6,"num":12
}
},
"userid":"8970ca285d9c4e4d",
"seatnum":12,
"session":"online"
}
}
I am able to get the userid and seatnum in the following way
JSONObject response = json.getJSONObject("response");
out.setUserid(response.getString("userid"));
out.setBalance(Double.valueOf(response.getString("balance")));
Now the problem is i need to parse the following content and need to get "num" value
"seatlist":
{
"seat":
{
"balance":85694.6,"num":12
},
"seat":
{
"balance":85694.6,"num":12
}
}
here is my code i am using
JSONObject objList = response.getJSONObject("seatlist");
String n = String.valueOf(objList.getJSONObject("seat"));
if(objList.getJSONObject("seat").get("userId").equals(userId))
{
String num = String.valueOf(objList.getJSONObject("seat").get("num"));
out.setSeatNum(Integer.valueOf(num));
}
if i have one seat value i am able to get "num" value else i am getting JSON exception
Pls give me a suggestion in this.....
You want to get a JSONArray in an JSONObject. That is not possible.
Get the Array and then iterate through the array to get the objects:
JSONObject objList = response.getJSONArray("seatlist");
for(int i = 0, i<objList.lenght(); i++){
JSONObject json = objList.get(i);
}
{
"response":
{
"seatlist":
{
"seat":
{
"balance":85694.6,"num":12
},
"seat":
{
"balance":85694.6,"num":12
}
},
"userid":"8970ca285d9c4e4d",
"seatnum":12,
"session":"online"
}
}
means an object with an object called response. this contains an object called seatlist. this contains 2 objects called seat (but this is wrong! this should be an array!). and so on..
to read this you can use
JSONObject json = new JSONObject(yourresponse);
JSONObject response = json.getJSONObject("response");
JSONObject seatlist = response.getJSONObject("seatlist");
JSONObject userid = response.getJSONObject("userid");
JSONObject seatnum = response.getJSONObject("seatnum");
JSONObject session = response.getJSONObject("session");
now seatlist contains.
{
"seat":
{
"balance":85694.6,"num":12
},
"seat":
{
"balance":85694.6,"num":12
}
}
which is wrong, since it contains 2 elements with same name. Now you can either call it by index like this:
JSONObject seat1 = seatlist.getJSONObject(1);
JSONObject seat2 = seatlist.getJSONObject(2);
seat1.getString("balanace"); seat1.getInt("num");
or you can iterate through the JSONObject.
At least it should be an Array instead of JSONOBject.
This means it should look like this.
{
"response": {
"seatlist": [
"seat":
{
"balance":85694.6,"num":12
},
"seat":
{
"balance":85694.6,"num":12
}
],
"userid":"8970ca285d9c4e4d",
"seatnum":12,
"session":"online"
}
}
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
This question already has answers here:
get the array index with value using arrayobject and store in array list
(2 answers)
Closed 10 years ago.
[ {
"question_id": 13,
"creation_date": 10,
"name": " certain degrees",
"tags": [
"android",
"sensor"
],
.....
...}
]
Here is the api I want to get the tags array ,the tag array contains only index and value,i want to get the array using array object and finally store in array list, i have tried but fail to get the error has been occured.
02-20 15:45:37.323: I/System.out(1165): org.json.JSONException: Value android at 0 of type java.lang.String cannot be converted to JSONObject
could anybody help me to solve this problem.
tagarray = questionobj.getJSONArray("tags");
for(int j=0;j<tagarray.length();j++){
//tagobject = tagarray.getJSONObject(j);//..if i comment this line the full array list is displaying but i need for each question allocated tags to display..am i clear..
//if(tagobject!=null){
tagname.add(tagarray.getString(j));
///tagname.add(0, null);
//}
}
your json format is not correct
try like that;
{"question":
{"question_id": "13",
"name": "certain degrees",
"tags": [{"android":"N", "sensor":"Y"}]
}}
You can use http://jsonviewer.stack.hu/, to be sure correction of your json data
I sugest you try this code,
import org.json.JSONArray;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String text = "[ { \"question_id\": 13, \"creation_date\": 10, \"name\": \"certain degrees\", \"tags\": [ \"android\", \"sensor\" ] } ]";
System.out.println(text);
JSONArray jsonArray = new JSONArray(text);
JSONObject jsonObjetc = jsonArray.getJSONObject(0);
JSONArray tagarray = jsonObjetc.getJSONArray("tags");
System.out.println(tagarray);
for(int j=0;j<tagarray.length();j++){
System.out.println(tagarray.getString(j));
}
}
}
Good luck, Aron
Try this,
ArrayList<String> list = new ArrayList<String>();
String text = "[ { \"question_id\": 13, \"creation_date\": 10, \"name\": \"certain degrees\", \"tags\": [ \"android\", \"sensor\" ] } ]";
try {
JSONArray jarray = new JSONArray(text);
for (int i = 0; i < jarray.length(); i++) {
JSONArray j_array = jarray.getJSONObject(i)
.getJSONArray("tags");
for (int j = 0; j < j_array.length(); j++) {
String str = j_array.getString(j);
list.add(str);
}
}
} catch (Exception e) {
}
Try This
tagarray = questionobj.getJSONArray("tags");
for(int j=0;j<tagarray.length();j++)
{
tagname.add(tagarray.getJSONObject(j).getString("android"));
}
How I filter this JSONArray that the JSONObject "name" contain "abcd"
{
"items":[{
"id":"082111",
"name":"abcd efgh"
}, {
"id":"082112",
"name":"abcd klmn"
}, {
"id":"082113",
"name":"klmn efgh"
}, {
"id":"082114",
"name":"abcd efgh"
}, {
"id":"082115",
"name":"efgh oprs"
}
]
}
And the result is must be
{
"items":[{
"id":"082111",
"name":"abcd efgh"
}, {
"id":"082112",
"name":"abcd klmn"
}, {
"id":"082114",
"name":"abcd efgh"
}
]
}
How I can get the result like that?
Should I convert the JSONArray to ArrayList, and filter when have converted to ArrayList, and convert again to JSONArray?
If yes, how i convert the JSONArray to ArrayList and filter it? And conver again to JSONArray?
Please give me samples code.
With the following code you'll get that which ever you required that is which are starting with the letters abcd like as you said.
JSONObject json = new JSONObject(jsonString);
JSONArray jData = json.getJSONArray("items");
for (int i = 0; i < jData.length(); i++) {
JSONObject jo = jData.getJSONObject(i);
if ((jo.getString("name")).startsWith("abcd", 0)) {
Log.i("Name is ", jo.getString("name"));
}
}
hi does anyone know how to create a Array that contains objects that in each objects contain several objects? i just can't seem to get my head round it
the structure should look like this
Array{[object]{subobject,subobject}
[object]{subobject,subobject}
}
heres what i have so far
JSONObject obj = new JSONObject(json2);
JSONObject objData = obj.getJSONObject("data");
fixturesArray = objData.getJSONArray("fixtures");
JSONArray FixArray = new JSONArray();
for(int t = 0; t < fixturesArray.length(); t++){
JSONObject fixObj = fixturesArray.getJSONObject(t);
String Matchdate = fixObj.getString("matchdate");
JSONObject DateObj = DateObj.put(Matchdate, DateObj);
heres my JSON essentially what i have if is a feed of fixtures i need to order them in to arrays of dates
{
"code":200,
"error":null,
"data":{
"fixtures":[
{
"kickoff":"15:00:00",
"matchdate":"2012-07-28",
"homescore":null,
"awayscore":null,
"attendance":null,
"homepens":null,
"awaypens":null,
"division_id":"5059",
"division":"Testing 1",
"comp":"LGE",
"location":null,
"fixture_note":null,
"hometeam_id":"64930",
"hometeam":"Team 1",
"awayteam_id":"64931",
"awayteam":"Team 2"
}, {
"kickoff":"15:00:00",
"matchdate":"2012-07-28",
"homescore":null,
"awayscore":null,
"attendance":null,
"homepens":null,
"awaypens":null,
"division_id":"5059",
"division":"Testing 1",
"comp":"LGE",
"location":null,
"fixture_note":null,
"hometeam_id":"64930",
"hometeam":"Team 1",
"awayteam_id":"64931",
"awayteam":"Team 2"
}
]
}
}
Do you mean that?:
JSONObject obj = new JSONObject();
obj.put("x", "1");
JSONObject parent_object = new JSONObject();
parent_object.put("child", obj);
JSONArray array = new JSONArray(parent_object.toString());
JSON String
{
"result": "success",
"countryCodeList":
[
{"countryCode":"00","countryName":"World Wide"},
{"countryCode":"kr","countryName":"Korea"}
]
}
Here below I am fetching country details
JSONObject json = new JSONObject(jsonstring);
JSONArray nameArray = json.names();
JSONArray valArray = json.toJSONArray(nameArray);
JSONArray valArray1 = valArray.getJSONArray(1);
valArray1.toString().replace("[", "");
valArray1.toString().replace("]", "");
int len = valArray1.length();
for (int i = 0; i < valArray1.length(); i++) {
Country country = new Country();
JSONObject arr = valArray1.getJSONObject(i);
country.setCountryCode(arr.getString("countryCode"));
country.setCountryName(arr.getString("countryName"));
arrCountries.add(country);
}
What I would suggest to do is to use JackSON JSON Parser library http://jackson.codehaus.org/ Then you can create a Class with the same fields as the JSON son the mapping from JSON To class will be direct.
So once you have all the items from JSON into a List of class you can order by dates or manipulate data as you want. Imagine that src is a String containing the JSON text. With JackSON lib you just need to do this.
ObjectMapper mapper = new ObjectMapper();
List<Fixture> result = mapper.readValue(src, new TypeReference<List<Fixture>>() { });
Here are two pieces of JSON which fit your description which is "Array that contains objects that in each objects contain several objects". The first method uses Arrays inside Objects. The other one uses Objects in Objects.
Method 1
[ { "name" : "first object in array" , "inner array" : [ { <object> } , { <object> } ] }
, { "name" : "second object in array" , "inner array" : [ { <object> } , { <object> } ] } ]
To parse the above you need two nested for loops (or something recursive).
Method 2
[ { "name" : "first object in array" , "first inner object" : { <object> } , "second inner object" : { <object> } } , <etc.> ] } ]
The second method can be parsed with a single for loop because you know in advance the number of inner objects to expect.