How to check JSON is empty in Android? - android

I am developing an Android Application which Fetch data from PHP Json.
I fetch the data of json successfully From JSON but my problem is when JSON is Empty it stops the application.
So I need to Know is How to know if the JSON is NULL or Return Nothing in ANDROID.
My empty JSON is:
[[]]
How to check that with Coding.
Please send me your suggestions.
My Full Code is On This Link:
Thanks Alot

JSONObject myJsonObject =
new JSONObject("{\"null_object_1\":[],\"null_object_2\":[null]}");
if (myJsonObject.getJSONArray("null_object_1").length() == 0) {
...
}

firstly you get key set of json.
Iterator<Object> keys = json.keys();
then check if any key exist then your json contain some value.
if(keys.hasNext()){ // json has some value
}
else
{
// json is empty.
}

after getting json from url first check for null by simply execute the code:-
if(yourjsonobject!=null){
//write your code here
}else{e
enter code here
//json is null
}

try like this,
if (<Your JSONobj>!= null ){
// do your parsing
}else{
}

1) json string "[[]]" means not empty jsonAarray it means your Outer JsonArray contains one element as JsonArray and your inner JsonArray is empty.
2) The reason your application is crashing/stopping is that JsonObject and JsonArray are incomptible types. You can not cast JsonArray to JsonObject. See
JsonArray and
JsonObject
3) You can always check the length of your JsonArray by
JsonArray#length() method.
also check
JsonArray#isNull if want to check wheter a JsonObject is NULL.
try {
JSONArray object = new JSONArray("[[]]");
if (object.length() > 0) {
JSONArray inner = object.getJSONArray(0);
if (inner.length() > 0) {
// do something
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

JSON Parsing on error body (JSON Exception) org . json.JSONException: End of input at character 0

I am getting an error org . json.JSONException: End of input at character 0
This is my Code :-
JSONObject jObjError = new JSONObject(response.errorBody().string());
Log.e("Error","::"+jObjError.getString("error_codes"));
and this is my JSON
{
"errors":{
"provider":["already has an appointment scheduled at this time."]
},
"error_codes":["provider_unavailable"]
}
Can anyone help me with this
The key point here is that you're trying to get a string from an array, not directly from an object. The correct way of parsing this would be:
JSONObject jObjError = new JSONObject(response.errorBody().string());
JSONArray errorArray = jObjError.optJSONArray("error_codes");
for(int i = 0;i<errorArray.size;i++) {
Log.e("Error","::"+errorArray.get(i));
}
If response is your returned JSON, you should pass it directly as parameter is it's of type String
JSONObject jo=new JSONObject(response);
and then do whatever else. because your error messages are customized and returned as json string so this is interpreted as successful request with customized messages.

Retrieve specific value inside array from json response in android

I need to get the value of idinside studentarray. The response I get is,
{
"response": {
"student": [
{
"id": "125745",
"module": 3,
"status": 1
}
]
}
}
I tried using following code,
String userId = null;
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
userId= object.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
But it doesn't work. How do I retrieve id?
You are almost there, just you need to do this:
JSONArray students = object.getJSONArray("student");
JSONObject student = students.getJSONObject(0);
userId= student.getString("id");
Because the id value is placed in a JSONObject, then inside a JSONArray at index 0, then it is again placed inside a JSONObject.
Also don't forget to handle exceptions, the code above, is just for your understanding.
Hope that helps!!
Your value is placed in json array. So, you need to retrieve response object using getJSONObject and then get student json array via getJSONArray. Then you will be able to iterate through student objects. There is no way to magically get id from json.
Alternatively, you can map your json to Java objects using Gson, for example.
Try this :
Let all of the json is called
String serverResponse = "Response from the server";
try {
JSONObject object = new JSONObject(serverResponse);
String userId = object.getJSONObject("response").getJSONArray("student").getJSONObject(0).getString("id");
}
catch (JSONException e) {
e.printStackTrace();
}
Hope this helps.
Assuming jsonObject is a reference to your root json, you can get id of the first student:
JSONObject response = (JSONObject) jsonObject.get("response");
JSONArray students = (JSONArray) response.get("student");
int id = (int) ((JSONObject)students.get(0)).get("id");

Parsing JSON in Java with variable number of objects [duplicate]

This question already has answers here:
Determine whether JSON is a JSONObject or JSONArray
(9 answers)
Closed 8 years ago.
My app receives a JSON response from web services and processes the data. The response that is received could have any number of objects. My normal method of parsing is:
JSONObject jsonObj = new JSONObject(json);
JSONArray arrChanges = jsonObj.getJSONObject("Changes").getJSONArray("Row");
for (int i = 0; i < arrChanges.length(); i++)
{
// do stuff
}
This normally gets the array Row inside the object Changes, and works fine. However, I tested it with only one record being returned, and suddenly got the error: JSONObject cannot be converted to JSONArray. After looking at the json, I can see that because there is now only one object, it is no longer a JSONArray, it is now just a JSONObject. Meaning that trying to use getJSONArray will obviously fail.
So my question is; considering I will receive a varying number of items (0 to lots), how can I reliably parse this data (without knowing how many records it will have)?
Try editing parsing with the help of this concept
if (<your jsonobject> instanceof JSONArray)
{
//parse as an jsonarray
for(....;....;...){
//your logic
}
}
else{
//parse as jsonobject without using any index value
}
hope this help you with your problem.
Force your json to be an array on the client side.
EDIT: I said client, I just mean wherever you are creating it.
var json = [];
json.push({"yourdataname":"yourdatavalue"});
Just another way to do it:
try{
JSONArray arrChanges = jsonObj.getJSONObject("Changes").getJSONArray("Row");
for (int i = 0; i < arrChanges.length(); i++)
{
// do stuff
}
}catch(JSONException e){
//i assume that the actual data is json array if not this block is called try jsonobject parsing here
// its something like try catch inside try catch
}

json.getJSONArray() throwing exception with one length one

I am having android with converts the JSON string to its original java object.
I am returning the List from REST server and it converts List into JSON format like this.
{"offerRideResult":[{"date":"06-APR-13 10.00.00.000000 AM","destination":"B","id":"57","PTripId":"87","req":"false","source":"A","srNo":"0","username":"Chinmay"},{"date":"06-APR-13 10.00.00.000000 AM","destination":"B","id":"1","PTripId":"88","req":"false","source":"A","srNo":"0","username":"chinmay91"}]}
On the client side that is android I am using the following method to convert it into java object.
try{
JSONObject obj=new JSONObject(response);
JSONArray arr=null;
arr=obj.getJSONArray("offerRideResult");
List<OfferRideResult> offerRideResult=new ArrayList<OfferRideResult>();
for(int i=0;i<arr.length();i++)
{
OfferRideResult res=new OfferRideResult();
res.setId(arr.getJSONObject(i).getInt("id"));
res.setPTripId(arr.getJSONObject(i).getInt("PTripId"));
res.setSrNo(arr.getJSONObject(i).getInt("srNo"));
res.setDate(arr.getJSONObject(i).getString("date"));
res.setSource(arr.getJSONObject(i).getString("source"));
res.setDestination(arr.getJSONObject(i).getString("destination"));
res.setReq(arr.getJSONObject(i).getBoolean("req"));
res.setUsername(arr.getJSONObject(i).getString("username"));
offerRideResult.add(res);
}
}catch(JSONException e)
{
System.out.println("Exception :- "+e);
}
It works fine when JSON format has two or more than two records but with on record it throws the following exception when input is like this.
{"offerRideResult":{"date":"05-APR-13 10.00.00.000000 AM","destination":"B","id":"1","PTripId":"89","req":"false","source":"A","srNo":"0","username":"chinmay91"}}
Error!!!org.codehaus.jettison.json.JSONException: JSONObject["offerRideResult"] is not a JSONArray
Can anybody please point my mistake or how can I deal with array of length one?
Thanks
but with on record it throws the following exception
use JSONObject.optJSONObject or JSONObject.optJSONArray for extracting next item from main JSONObject.try it as:
JSONObject obj=new JSONObject(response);
JSONArray arr=null;
JSONObject jsonobj=null;
// get offerRideResult JSONArray
arr=obj.optJSONArray("offerRideResult");
if(arr==null){
// means item is JSONObject instead of JSONArray
jsonobj=obj.optJSONObject("offerRideResult");
}else{
// means item is JSONArray instead of JSONObject
}
Because the json with only one results is not an array it's not going to be read correctly by getJSONArray()
either you can make your json string more like:
{"offerRideResult":[{"date":"05-APR-13 10.00.00.000000 AM","destination":"B","id":"1","PTripId":"89","req":"false","source":"A","srNo":"0","username":"chinmay91"}]}
or read it in as a single object like #ρяσѕρєя K proposes.

How to read JSON parent tags in Android

I need your help with following matter. I want to read the parent tags of a JSON file. Below is my JSON file content;
{
"ebook":
[
{"id":"1","name":"book1"},
{"id":"2","name":"book2"}
],
"ebrochure":
[
{"id":"1","name":"brochure1"},
{"id":"2","name":"brochure2"}
],
"emenu":
[
{"id":"1","name":"menu1"},
{"id":"2","name":"menu2"}
]
}
I just need to find out how many parents tags in the JSON and what are they. According to my given JSON file the answers should be 3 (there are 3 parent JSON tags) and "ebooks, ebrochure, emenu" (names of the parent tags). Is ther any JAVA class I can get my work done?
I know how to read a full JSON file. First we pass the JSON to a JSONObject and then pass children to a JSONArray by using getJSONArray() method.
But getJSONArray() method needs the name of the parent tag. According to my example it can be ebook, ebrochure or emenu. Assume there is a circumstance where we can't see the content of the JSON only access the URL. In such a situation I need to find out how many parents tags are there and what are the names of them.
That's my problem. Thanks in advance for helping me :-)
You should read the documentation for JSONObject.names
Basically, names()(in Android) can be used to get an array of field names, and then use those as your keys. I won't do a full example here because you'll learn better if you try for yourself.
public static String Fechingdata(String response){
Id1.clear();
Id2.clear();
Id3.clear();
name1.clear();
try{
JSONArray jsonarray = new JSONArray("["+response+"]");
JSONObject jsonobject = jsonarray.getJSONObject(0);
parseForResponse1(jsonobject.getString("ebook"),1);
parseForResponse2(jsonobject.getString("ebrochure"),2);
parseForResponse3(jsonobject.getString("emenu"),3);
return response;
}catch (Exception e) {
return "\"" + "Access Denied" + "\"";
}
}
private static void parseForResponse1(String res,int i) {
try{
JSONArray jsonarray1 = new JSONArray(res);
Log.d("jsarry1",""+jsonarray1.length());
for(int i=0;i<jsonarray1.length();i++){
JSONObject jsonobject = jsonarray1.getJSONObject(i);
if(i ==1){
Id1.add(jsonobject.getString("id"));
name1.add(jsonobject.getString("id"));
}
if(i ==2){
Id2.add(jsonobject.getString("id"));
name2.add(jsonobject.getString("id"));
}
if(i ==2){
Id3.add(jsonobject.getString("id"));
name3.add(jsonobject.getString("id"));
}
}
}
catch (Exception e) {
System.out.println(e.toString());
}
}
This try this json parsging
JSONObject jobj = new JSONObject(Your Json String);
JSONArray jarray=jobj.names();
for(int i=0;i<jarray.length();i++){
Log.e("parenttag",jarray.getString(i));
}
by this u will get all parent tag u have in your jsonString

Categories

Resources