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.
Related
I am calling a REST API using the android app, the results of the POST method API is as follows:
{
"Items": {
"ap_id": "37",
"ap_time_from": "14:28",
"ap_time_to": "16:28",
"patient_id": "153",
"patient_name": "Nikhil",
"patient_email": "a#a.com",
"patient_location": "abc"
} }
Converting it into readable data using:
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("Items");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
DoctorModel doctorModel1 = new DoctorModel();
doctorModel1.setApp_id(object.getString("ap_id"));
doctorModel1.setStart_timing(object.getString("ap_time_from"));
doctorModel1.setEnd_timing(object.getString("ap_time_to"));
doctorModel1.setUser_id(object.getString("patient_id"));
doctorModel1.setUser_name(object.getString("patient_name"));
doctorModel1.setUser_mail(object.getString("patient_email"));
doctorModel1.setLocation(object.getString("patient_location"));
doctorModelList.add(doctorModel1); }
Now when I am trying to convert it so that I can display the results in a recycler view I am getting the following error:
org.json.JSONException: Value
{"ap_id":"37","ap_time_from":"14:28","ap_time_to":"16:28","patient_id":"153","patient_name":"Nikhil","patient_email":"a#a.com","patient_location":"abc"}
at Items of type org.json.JSONObject cannot be converted to JSONArray
I have been using the same way of converting the JSON Object data into JSON Array, not sure where I am going wrong. Any help would be appreciated, thanks!
You need to have an array as an object inside Items, as follows :
{
"Items":
[
{
"ap_id": "37",
"ap_time_from": "14:28",
"ap_time_to": "16:28",
"patient_id": "153",
"patient_name": "Nikhil",
"patient_email": "a#a.com",
"patient_location": "abc"
}
]
}
Else, change your code to support single object instead of an array
JSONObject jsonObject = new JSONObject(response);
JSONArray object = jsonObject.JSONObject("Items");
In the current response, the value of Items has a JSON object, not a JSON array. That's why this exception happens. To convert this response to data model then you can use this:
JSONObject jsonObject = new JSONObject(response);
JSONArray object = jsonObject.JSONObject("Items");
DoctorModel doctorModel1 = new DoctorModel();
doctorModel1.setApp_id(object.getString("ap_id"));
doctorModel1.setStart_timing(object.getString("ap_time_from"));
doctorModel1.setEnd_timing(object.getString("ap_time_to"));
doctorModel1.setUser_id(object.getString("patient_id"));
doctorModel1.setUser_name(object.getString("patient_name"));
doctorModel1.setUser_mail(object.getString("patient_email"));
doctorModel1.setLocation(object.getString("patient_location"));
doctorModelList.add(doctorModel1);
Or if you want to get the array from json then the JSON will look like this:
{
"Items":
[
{
"ap_id": "37",
"ap_time_from": "14:28",
"ap_time_to": "16:28",
"patient_id": "153",
"patient_name": "Nikhil",
"patient_email": "a#a.com",
"patient_location": "abc"
}
]
}
Hope you understand the isse.
JSONArray jsonArray = jsonObject.getJSONArray("Items"); // this line getting exception because you are trying to convert JSONObject("Items") into JSONArray.
you have to make some changes in the response: 1. If you want to return "Items" as Array in Response.
{
"Items": [
{
"ap_id": "37",
"ap_time_from": "14:28",
"ap_time_to": "16:28",
"patient_id": "153",
"patient_name": "Nikhil",
"patient_email": "a#a.com",
"patient_location": "abc"
}
]
}
If you want to return "Items" like an object in Response then you have to change in code like this
JSONObject jsonObject = new JSONObject(response);
JSONObject jsonObjectItem = jsonObject.getJSONObject("Items");
But in the second case, you can not get the result in the form of an array.
1.I am having json object like this how can i get the access to all values in android
2.before anyone down voting that i want to say i have searched stackoverflow for similar examples but those examples contains JSONObject and then JSONArray
3.Here in my case everything is JSONObject so i'm little bit confused
{
"1":
{"sno":"10","latitude":"31.249441437085455","longitude":"75.70003598928452"},
"2":
{"sno":"11","latitude":"31.249398442090207","longitude":"75.70003397762775"}
}
This is how i made it to JSONObject
1.Below code returned me output like that which is all JSONObject
2.Is there any way to make "1" and "2" as JSONArray ?
$select_rows = "select sno,latitude,longitude from activities where username='$username'";
if ($result = mysql_query($select_rows)) {
$num_of_fields = mysql_num_fields($result);
$num_of_rows = mysql_num_rows($result);
$i = 0;
$j = 1;
while ($retrieved = mysql_fetch_array($result)) {
for ($i = 0; $i < $num_of_fields; $i++) {
$field_name = mysql_field_name($result, $i);
$object[$j][$field_name] = $retrieved[$field_name];
}
$j++;
}
echo json_encode($object);
}
Hope this may help you
JSONObject jsonObject=new JSONObject(result);
jsonObject=jsonObject.getJSONObject("1");
Double lat=jsonObject.getDouble("latitude");
Toast.makeText(getBaseContext(),""+ lat, Toast.LENGTH_LONG).show();
Better create a valid JSONArray to make things easier. When you create the JSON string , don't append the index. I believe your are reading the data from sqlite and generating the JSON string.
Also change the outer { (curly brace) to [ (square bracket) to represent as Array element. So your json string will be like this
[
{
"sno": "10",
"latitude": "31.249441437085455",
"longitude": "75.70003598928452"
},
{
"sno": "11",
"latitude": "31.249398442090207",
"longitude": "75.70003397762775"
}
]
Then , you can simply get its as JSONArray
JSONArray jsonArray = new JSONArray(jsonString);
And then read each element in array item
for(int index = 0;index < jsonArray.length(); index++) {
JSONObject jsonObject = jsonArray.getJSONObject(index);
}
To get one of your inner JSONObject elements, you'll need to get it from the outer one using getJSONObject(String key).
Sample code:
JSONObject item1 = myJson.getJSONObject("1");
//item1 now contains {sno:10,latitude:31.2...etc}
//now you can get the individual values out of the resulting JSON Object
//for example, getting the latitude
double lat = item1.getDouble("latitude");
Hey guys this is the first time I am doing JSON and I have gotten the json from the server. Now my only question is how do I take the data.
The JSON includes
[
{
"name": "Joe Smith",
"employeeId":1,
"company": "ABC",
"phone": {
"work": "555-555-5555",
"home": "666-666-6666",
"mobile": "777-777-7777"
}
},
{
"name": "Does Smith",
"employeeId":2,
"company": "XYZ",
"phone": {
"work": "111-111-1111",
"home": "222-222-2222",
"mobile": "333-333-3333"
}
}
]
jsonData is my string of the JSON
Currently I have:
JSONObject json = new JSONOBject(jsonData);
JSONObject data = json.getJSONObject(*******)
JSONArray phones = data.getJSONArray("phone");
not sure what to put on the second line. Also, what is the best way to group the information.
Please make it easy to understand, not exactly a professional yet haha
Thanks!
Your first line is wrong because current string is JSONArray of JSONObject's so get data from current string as:
JSONArray json = new JSONArray(jsonData);
for(int i=0;i<json.length();i++){
JSONObject data = json.getJSONObject(i);
// get name,employeeId,... from data
String str_name=data.optString("work");
//...
JSONObject jsonobjphones = data.getJSONObject("phone");
// get work from phone JSONObject
String str_work=jsonobjphones.optString("work");
//....
}
Try this
List list=new ArrayList();
JSONObject jObject = new JSONObject(str_response_starter);
JSONArray json_array_item_id = jObject.getJSONArray("itemid");
System.out.println("json array item id"+json_array_item_id);
JSONArray json_array_item_name = jObject.getJSONArray("itemname");
System.out.println("json array item name"+json_array_item_name);
JSONArray json_array_item_type = jObject.getJSONArray("type");
System.out.println("json array item type"+json_array_item_type);
JSONArray json_array_item_cost = jObject.getJSONArray("cost");
System.out.println("json array item cost"+json_array_item_cost);
Now
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvPairs.size());
String k, v;
Iterator<String> itKeys = kvPairs.keySet().iterator();
while (itKeys.hasNext()) {
k = itKeys.next();
System.out.println(" value of k"+k);
v = kvPairs.get(k);
System.out.println(" value of v"+v);
In JSON, [] represents JSONArray, {} represents JSONObject. In your JSON string, it starts with [, so you need to start with JSONArray:
JSONArray people = new JSONArray(jsonData);
And then you'll notice that each person is a JSONObject, so now you need to loop them in order to get their information:
for(int i=0;i<people.length();i++){
JSONObject person = people.getJSONObject(i);
JSONObject phones = person.getJSONObject("phone"); //phone is also a JSONObject, because it starts with '{'
String workPhone = phones.get("work");
}
Want Android Code For Following JSON Format...Bit Confused How to fetch value of array For Following Pattern..
{
"params": [
{
"answer_data_all": [
{
"id": "5",
"question_id": "14"
}
],
"form_data_all": [
{
"id": "1",
"name": "form 1"
}
]
}
]
}
You just have some nested JSONArray and JSONObject. Assuming you have this response in string format all you have to do is create JSONObject from that string and then extract what you need. As someone mentioned [ ] encloses JSONArray while { } encloses JSONObject
JSONObject mainObject = new JSONObject(stringResponse);
JSONArray params = mainObject.getJSONArray("params"); //title of what you want
JSONObject paramsObject = params.getJSONObject(0);
JSONArray answerData = paramsObject.getJSONArray("answer_data_all");
JSONArray formData = paramsObject.getJSONArray("form_data_all");
String id = formData.getJSONObject(0).getString("id");
You should be able to extract all the values doing something like this. Although I will say I think the formatting is odd. You're using single member arrays that just contain other objects. It would make much more sense to either use one array to hold all the object or just separate JSONObject. It makes it much easier to read and easier to parse.
Parsing a JSON is fairly simple. You could use GSON library by Google for example. Below is an example I wrote for your object/model:
class MyObject{
ArrayList<Params> params;
class Params {
ArrayList<AnswerData> answer_data_all;
ArrayList<FormData> form_data_all;
class AnswerData {
String id;
String question_id;
}
class FormData {
String id;
String name;
}
}
}
And then get an instance of your object with:
MyObject myObject = (MyObject) (new Gson()).toJson("..json..", MyObject.class);
JSONArray feed = feedObject.getJSONArray("params");
for(int i = 0; i<feed.length(); i++){
JSONArray tf = feed.getJSONArray(i);
for (int j = 0; j < tf.length(); j++) {
JSONObject hy = tf.getJSONObject(j);
String idt = hy.getString("id");
String name = hy.getString("name");
}
}
**NOTE: the 'feedObject' variable is the JSONObject you are working with..Although this your type of JSON feed is kinda mixed in terms of string names and all but this should do for now..
I'm trying to find the value in jsonObject distance (which is 10194)
{
"destination_addresses" : [ "Burnaby, BC, Canada" ],
"origin_addresses" : [ "Vancouver, BC, Canada" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "10.2 km",
"value" : 10194
},
"duration" : {
"text" : "19 mins",
"value" : 1118
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I wrote this code but it gives me null
rows = jObj.getJSONObject(TAG_ROWS);
JSONArray elements = new JSONArray (rows.getString(TAG_ELEMENTS));
for (int i=0; i<elements.length();i++){
JSONObject obj = elements.optJSONObject(i);
JSONObject distance = obj.getJSONObject(TAG_DISTANCE);
value= distance.getString(TAG_VALUE);
any idea ??
You gonna have to do something as below
try {
JSONObject jsonObj = new JSONObject(YOUR-JSON-STRING-HERE);
String destination = jsonObj.getString("destination_addresses");
// printing the destination and checking wheather parsed correctly
Log.v("Destination", destination);
JSONArray jarRow = jsonObj.getJSONArray("rows");
for(int i=0;i<jarRow.length(); i++){
// creating an object first
JSONObject ElementsObj = jarRow.getJSONObject(i);
// and getting the array out of the object
JSONArray jarElements = ElementsObj.getJSONArray("elements");
for(int j=0; j<jarElements.length(); j++){
JSONObject distanceObj = jarElements.getJSONObject(j).getJSONObject("distance");
String distanceStr = distanceObj.getString("value");
Log.v("finally getting distance : ", distanceStr);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
here is a screen shot from DDMS
According to your JSON, even rows is of the type JSONArray, but you're fetching rows, this way
rows = jObj.getJSONObject(TAG_ROWS);
Hence, the problem.
You need to fetch rows like this:-
JSONArray rows = jObj.getJSONArray(TAG_ROWS);
The object 'rows' must be typed JSONArray since what it contains is an array. After that you must do another for and get the other array that is 'elements' and then do the loop for the second array. You must get something like:
rows = jObj.getJSONArray(TAG_ROWS);
for (int i=0; i<rows.length();i++){
JSONArray elements = new JSONArray (rows.getString(TAG_ELEMENTS));
for (int j=0; j<elements.length();j++){
JSONObject obj = elements.optJSONObject(j);
JSONObject distance = obj.getJSONObject(TAG_DISTANCE);
value= distance.getString(TAG_VALUE);
}
}