Unable to convert JSONObject into JSONArray - android

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.

Related

How to parse json data which has multiple jsonArrays in android?

I have JSON data like this,it is having multiple jsonArrays in it.how to parse this type of data?
{
"result":
[{
"site_name":"comenius",
"ws_url":"https://comenius-api.sabacloud.com/v1/",
"base_url":"https://comenius.sabacloud.com/",
"logo_url":"",
"Title":"",
"menu_items":[
{"item":
[{"id":"home1","label":"Home" }]
},
{"item":
[{"id":"enrol1","label":"Enrollment" }]
},
{"item":
[{"id":"transcripts1","label":"Completed Courses"}]
},
{"item":
[{"id":"goals1","label":"Goals"}]
},
{"item":
[{"id":"rprojects1","label":"Reference Projects"}]
},
{"item":
[{"id":"iwh1","label":"Internal Work History"}]
},
{"item":
[{"id":"ewh1","label":"EXternal Work History"}]
}
]
},{.....}
]
}
i need to parse the data and get the values of id,label ,i write some code to parse the data but it didnt work.
JSONObject subObj = new JSONObject(data2);
JSONObject innerObj1 = subObj.getJSONObject("result");
JSONObject subArrayObj = innerObj1.getJSONObject("menu_items");
for(int j =0;j < subArrayObj.length();j++) {
JSONObject innsersubObj = subArrayObj.getJSONObject("item");
String id = innsersubObj.getString("id");
String label = innsersubObj.getString("label");
Log.e("id",id);
Log.e("label",label);
}
How to parse the data any thing need to change in the code ?
You have to use JSONObject and JSONArray are different objects, you have to use correct class:
JSONArray resultArray = subObj.getJSONArray("result");
JSONObject firstItem = resultArray.getJSONObject(0);
JSONArray menuItems = firstItem.getJSONArray("menu_items");
etc.
JSONARRAY subArrayObj = innerObj1.getJSONARRAY("menu_items");
Since menu_items is returning an array..it should be collected in an array object..

JSON Handling Quick

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

How to check JSON object and array

I have 2 links; which gives json data. I am trying to get the values from the urls from the same activity in android using asynTask. did the coding till converting the data to string(stored it in jsonStr1). But now comes the problem. Because,among the 2 urls:
one starts with JSON object-
{ "contacts": [ {"id": "c200", "name": "Ravi Tamada" },
{ "id": "c201", "name": "Johnny Depp" }
]
}
another start with JSON array-
[{"appeId":"1","survId":"1"},
{"appeId":"2","survId":"32"}
]
Now how am i going to give a condition for them whether to know its a JSON array or Object? JSON array are object that i know but cant find how to separate them. i have tried the below:
JSONObject jsonObj = new JSONObject(jsonStr1);
if(jsonObj instanceof JSONArray){}
but if condition is showing error- incompatible conditional operand types JSONObject and JSONArray
You can simply use startsWith for String to check where the String starts with { or [
boolean isJsonArray = jsonResponse.startsWith("[");
if(isJsonArray){
// Its a json array
}
else{
// Its a json object
}
You can use JSONTokener class for that, here is a sample code for that.
Object json = new JSONTokener(response).nextValue();
if (json instanceof JSONObject){
JSONObject result = new JSONObject(response);
}
else if (json instanceof JSONArray){
JSONArray resultArray = new JSONArray(response);
}
make jsonobject and call which place u want to calling
jsonobject = JSONfunctions
.getJSONfromURL("http://ampndesigntest.com/androidapi/CURRENTPROJECTDATA/textfiles/hotels");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("worldpopulation");
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("rank", jsonobject.getString("rank"));
map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));
map.put("flag", jsonobject.getString("flag"));
// map.put("latlongitude", jsonobject.getString("latlongitude"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
You could use the method has(String) to check if the JSONObject contains or not the key contacts.
if(jsonOjbect.has("contacts") {
...
}
else {
...
}

Recieving json array and saving in variables. Android

So I am receiving a JSON array in an httpresponse. The array consists of the following objects/variables.
{"sessid":"vxkEXkMBUmBByESRlvaxrxSaFTfhDqd8","session_name":"SESS88cdfb2f1c420898","user":{"uid":"60","name":"abc","theme":"","signature":"","signature_format":"filtered_html","created":"13082976","access":"1386287","login":1386211,"status":"1","timezone":null,"language":"","picture":null,"data":{"mimemail_textonly":0},"roles":{"2":"authenticated user","5":"centre user"},"field_centre_reference":{"und":[{"nid":"256"}]},"field_first_name":{"und":[{"value":"web","format":null,"safe_value":"web"}]},"field_surname":{"und":[{"value":"services","format":null,"safe_value":"services"}]},"bounce_mail_blocked":false,"force_password_change":"0"}}
Now I want to receive all these objects/strings in separate variables. Like i want to store the "sessid" in a variable String session_id. And so on. I can get the first two (i.e. sessid and session_name) in a simple way with the help of the following code.
response = client.execute(httppost);
BasicResponseHandler handler = new BasicResponseHandler();
String data = handler.handleResponse(response);
jObj = new JSONObject(data);
sessid = jObj.getString("sessid");
Log.d("sessid obj", sessid);
session_name = jObj.getString("session_name");
Log.d("session_name", session_name);
But since I am a noob at Android, I don't know how to get the rest of the data to be saved in variables. The upcoming data cannot be saved in a simple way.
Try with this:
JSONObject j_user = jObj.getJSONObject("user");
String uid = j_user.getString("uid");
...
//And so on with the rest of the fields
{ // json object node
"sessid": "vxkEXkMBUmBByESRlvaxrxSaFTfhDqd8",
"session_name": "SESS88cdfb2f1c420898",
"user": { // json object user
"uid": "60", // string
"name": "abc",
"theme": "",
"signature": "",
"signature_format": "filtered_html",
"created": "13082976",
"access": "1386287",
"login": 1386211,
"status": "1",
"timezone": null,
"language": "",
"picture": null,
"data": { // json object data
"mimemail_textonly": 0 //string
},
....// rest of the json
{ represents json object node
[ represents json array node
To parse
JSONObject jObj = new JSONObject(load());
String sessid = jObj.getString("sessid");
Log.d("sessid obj", sessid);
JSONObject user = jObj.getJSONObject("user");
String uid = user.getString("uid");
Log.d("sessid obj", uid);
To parse data
"data": {
"mimemail_textonly": 0
},
JSONObject data= user.getJSONObject("data");
Log.i(".......",""+data.getString("mimemail_textonly"));
To parser field_centre_reference
"field_centre_reference": { // json object field_centre_reference
"und": [ // json array und
{ // json object node
"nid": "256" //string
}
]
},
JSONObject field= user.getJSONObject("field_centre_reference");
JSONArray jr = field.getJSONArray("und");
JSONObject jb1 = (JSONObject) jr.get(0);
Log.i(".......",""+jb1.getString("nid"));
Check out JacksonParser library, it provides annotations which make your work so easy. And it is one of fastest parsing libraries... You can have it here
Edit:
As an example you can take a look at one of my previous question JacksonParser databind and core cause "Found duplicate file for APK"?
You should notice that the JSON you received is a nested JSON. It is like a Map that one of the value of Map is also a Map.
In your case, there is a JSONObject contains sessid and session_name while is only string, but the "user" is also a JSONObject, so you can parse it level by level.
For more details, you can read http://www.vogella.com/articles/AndroidJSON/article.html
Try this..
Getting
"user": {
"uid": "60",
JSONObject obj_user = jObj.getJSONObject("user");
String uid = obj_user.getString("uid");
"user": {
"uid": "60",
"data": {
"mimemail_textonly": 0
}
JSONObject obj_data = jObj.getJSONObject("data");
String mimemail_textonly = obj_user.getString("mimemail_textonly");
JSONObject obj_roles = jObj.getJSONObject("roles");
String two = obj_roles.getString("2");
"field_centre_reference": {
"und": [
{
"nid": "256"
JSONObject obj_field_centre_reference = jObj.getJSONObject("field_centre_reference");
JSONArray ary_und = obj_field_centre_reference.getJSONArray("und");
JSONObject objve = ary_und.getJSONObject(0);
String nid= objve.getString("nid");

Android create a JSON array of JSON Objects

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.

Categories

Resources