How to check JSON object and array - android

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

Related

Unable to convert JSONObject into JSONArray

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.

How to parse JSON using hardocoded values

I am trying to parse json but it gives me exception.
I hardcoded expected json as String like this
String stringJSON="[{\"value1\":\"ABC567123\",\"end_at\":\"08/28/2014 09:10:00\",\"start_at\":\"04/25/2016 09:20:00\"}]";
Valid json is like this
[
{
"value1": "ABC567123",
"end_at": "08/28/2014 09:10:00",
"start_at": "04/25/2016 09:20:00"
}
]
Now I am trying to parse json like below and getting exception.
JSONObject responseObJ;
try {
responseObJ= new JSONObject(stringJSON); //error here
if(responseObJ!=null){
//do something
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
Please suggest what to do?
//hard coded it for temporary - json result is expected to exact same
stringJSON is contains JSONArray instead of JSONObject as root element in JSON String.
Either remove [] from start and end of String according to current code or if multiple JSONObject's is available in JSONArray then get JSONArray from stringJSON :
JSONArray responseObJ= new JSONArray(stringJSON);
[ ] they show that it has an array of objects in it so you can retrieve it like this
JSONArray jsonArray= new JSONArray(stringJSON);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jObject.getJSONObject(i);
// here you can get the values of objects stored in the jsonObject
}
In your case you have only one object so you don't have to use loop instead you can get it like this
JSONArray jsonArray= new JSONArray(stringJSON);
JSONObject jsonObject = jObject.getJSONObject(0);
yes as you said its valid json but its JsonArray not JsonObject.
Just remove [] from start and end.
your string should be
String stringJSON="{\"value1\":\"ABC567123\",\"end_at\":\"08/28/2014 09:10:00\",\"start_at\":\"04/25/2016 09:20:00\"}";
or if you want to work with current string then use JsonArray instead of JsonObject
JSONArray responseObJ= new JSONArray(stringJSON);
Can you try Deserialize method of ScriptSerializer class? Like:
var scriptSerializer = new JavaScriptSerializer();
var obj = scriptSerializer.Deserialize<Object>(str);

Populating Spinner data from json

I have some problem... when i try to populating spinner data from json
this, my json data :
parse bank and product work normally
Bank.
Product.
Provider no data
Log.
what should i do to parse provider to android spinner ?
Try this..
provider is inside product array
"product": [ // JSONArray
{ // JSONObject
"id": "1",
"value": "PULSA",
"name": "Pulsa Telpon",
"provider": [ // JSONArray
Code
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONObject product_obj = jsonObj.getJSONArray("product").getJSONObject(0);
JSONArray categories = product_obj
.getJSONArray("provider");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("id"),
catObj.getString("name"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Here you are trying to fetch provider jsonArray from the jsonobject formed using the json response json.
JSONArray categories = jsonObj.getJSONArray("provider");
however the provider jsonArray is not in the base jsonobject, but it is in the product jsonArray. That is why you are not getting any data for provider.
Solution :
first get the product jsonarray from the base jsonobject. Then extract the provider jsonarray for each product in loop.
Algorithm or Flow:
JSONObject jsonObj = new JSONObject(json); // Base json object
JSONArray bankArray = jsonObj.getJSONArray("bank"); // Bank json array
JSONArray productArray = jsonObj.getJSONArray("product"); // Product json array
// no. of items in product
int arrayLength = productArray.length();
for (int i = 0; i < arrayLength; i++) {
// get single product object from array
JSONObject singleProductObject = productArray
.getJSONObject(i);
// Get the provider array for every product
JSONArray providerArray = singleProductObject.getJSONArray("provider");
}
This way you will get the provider data.
Hope it helps you.
What I understand your Json object contains to memeber that is a array bank and product
provider is inner array od product.
I am not sure if you take care of this
try this only for single product
JSONArray categories = jsonObj.getJSONArray("product")[0].getJSONArray("provider");

parsing json in Android with different with inner array

I have this json url which outputs this (snippet)
{
"status":true,
"result":{
"message":"Successfully retrieved the daily feed.",
"items":{
"1376438400":[
{
"code":"DjCr3N3o",
"slug":"soulja-boy-gets-kicked-off-airplane",
"cdn_screenshot_path":"screenshots\/2013\/08\/DjCr3N3o.png",
"title":"Soulja Boy Gets Kicked Off Airplane!",
"hits":"457",
"date_added":"1376507797"
},
{
"code":"7V9eOVpX",
"slug":"dr.-dre-and-suge-knight-baby-mama-michelle-surprise-performance-she-sounds-like-a-chipmunk-but-sings-like-an-angel",
"cdn_screenshot_path":"screenshots\/2013\/08\/7V9eOVpX.png",
"title":"Dr. Dre AND Suge Knight Baby Mama Michel'le Surprise Performance! (She Sounds Like A Chipmunk But Sings Like An Angel!)",
"hits":"525",
"date_added":"1376505010"
},
{
"code":"8ovO203r",
"slug":"headless-snake-bites-itself-in-the-butt",
"cdn_screenshot_path":"screenshots\/2013\/08\/8ovO203r.png",
"title":"Headless Snake Bites Itself In The Butt!",
"hits":"361",
"date_added":"1376485812"
}
],
"1376352000":[
{
"code":"9b9jR6qs",
"slug":"show-you-how-to-do-this-son-chris-paul-hits-4-straight-jumpers-on-colleges-best-point-guards",
"cdn_screenshot_path":"screenshots\/2013\/08\/9b9jR6qs.jpg",
"title":"Show You How To Do This Son! Chris Paul Hits 4 Straight Jumpers On College's BEST Point Guards!",
"hits":"979",
"date_added":"1376443810"
},
{
"code":"p6l5pwg8",
"slug":"ttbnez-fck-da-opp-music-video",
"cdn_screenshot_path":"screenshots\/2013\/08\/p6l5pwg8.png",
"title":"TTBNEZ - F*ck Da Opp [Music Video]",
"hits":"316",
"date_added":"1376419812"
},
{
"code":"haxUoUVt",
"slug":"strip-life-the-reality-series-feat.-lanipop-entyce-trailer",
"cdn_screenshot_path":"screenshots\/2013\/08\/haxUoUVt.png",
"title":"Strip Life: The Reality Series (feat. Lanipop, Entyce) [Trailer]",
"hits":"426",
"date_added":"1376419214"
}
],
The problem I am having is figuring out how to parse it due to its format and how to reach the data such as "code", "slug" and "title". This is what I have so far, but it seems wrong as I may have to have 2 loops instead of 1 I think.
This is what I have so far
#Override
protected Void doInBackground(Void... params) {
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrive JSON Objects from the given website URL in JSONfunctions.class
jsonobject = JSONfunctions
.getJSONfromURL("http://api.hoodplug.com/v1/videos/daily_feed?per_page=5&offset=0&format=json");
try {
// Locate the array name
jsonarray = jsonobject.getJSONArray("item");
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("code", jsonobject.getString("code"));
map.put("slug", jsonobject.getString("slug"));
map.put("title", jsonobject.getString("title"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
You're just missing a little point here!
in here you got the first json object :
jsonobject = JSONfunctions
.getJSONfromURL("http://api.hoodplug.com/v1/videos/daily_feed?per_page=5&offset=0&format=json");
this json object is the whole big JSON object that contain status and result but you directly want to access the JSON array that inside result object! using this :
// Locate the array name
jsonarray = jsonobject.getJSONArray("items");
The right thing is you must get the result object first from the big json object with
JSONObject resultObject = jsonobject.getJSONObject("result");
then use the resultObject to get the array!
try {
// Locate the array name
jsonarray = resultObject .getJSONArray("item");
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("code", jsonobject.getString("code"));
map.put("slug", jsonobject.getString("slug"));
map.put("title", jsonobject.getString("title"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
I hope you understand my answer, but if you have other question about my answer feel free to ask! :)

How to call the JSON object in Android

I am new to the android development. i am having the following android code to call the json
try {
JSONObject jsonObject = new JSONObject(result);
//JSONObject object = jsonObject.getJSONObject("CUSTOMER_ID");
JSONArray jArray = new JSONArray(CUSTOMER_ID);
returnUsername1 = jArray.getInt("CUSTOMER_ID");
Toast.makeText(getApplicationContext(), ""+returnUsername1,Toast.LENGTH_LONG).show();
for (int i = 0; i < jArray.length(); i++) {
}
My JSON format is like [[{"0":"1","CUSTOMER_ID":"1"}]].
i refer some json format it should like [{"0":"1","sno":"1"}] i can understand this.But mine is different from this.
how can i call the customer_id using the above code.anyone can suggest a solution.
What you have is a Json Array
JSONArray jsonarray = new JSONArray(result); // result is a Array
[ represents json array node
{ represents json object node
Your Json. Do you need a Json array twice?
[ // array
[ //array
{ // object
"0": "1",
"CUSTOMER_ID": "1"
}
]
]
Parsing
JSONArray jsonArray = new JSONArray(result);
JSONArray ja= (JSONArray) jsonArray.get(0);
JSONObject jb = (JSONObject) ja.get(0);
String firstvalue = jb.getString("0");
String secondvalue = jb.getString("CUSTOMER_ID");
Log.i("first value is",firstvalue);
Log.i("second value is",secondvalue);
LogCat
07-22 14:37:02.990: I/first value is(6041): 1
07-22 14:37:03.048: I/second value is(6041): 1
Generally, to get a JSONObject from a JSONArray:
JSONObject jsonObject = jsonArray.getJSONObject(0); //0 -> first object
And then
int userID = jsonObject.getInt("CUSTOMER_ID");
CUSTOMER_ID is not considered a JSONObject in this case. If jsonObject is what you think it is, then you should be able to access it with jsonObject.getString("CUSTOMER_ID")
if you have any problems regarding to your JSON format first validate it through this site
http://jsonlint.com/
then for parsing
JSONObject jsonObject = new JSONObject(result);
// since your value for CUSTOMER_ID in your json text is string then you should get it as
// string and then convert to an int
returnUsername1 = Integer.parseInt(jsonObject.getString("CUSTOMER_ID"));
Try this
JSONObject jsonObject = new JSONObject(result);
JSONArray jArray =json.getJSONArray("enterjsonarraynamehere");
for (int i=0; i < jArray.length(); i++)
{
try {
JSONObject oneObject = jArray.getJSONObject(i);
// Pulling items from the array
String cust= oneObject.getString("CUSTOMER_ID");
} catch (JSONException e) {
// Oops something went wrong
}
}
Im assuming your json is something like this
<somecode>
{
"enterjsonarraynamehere": [
{ "0":"1",
"CUSTOMER_ID":"1"
},
{ "0":"2",
"CUSTOMER_ID":"2"
}
],
"count": 2
}
<somecode>

Categories

Resources