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

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
}

Related

Parsing JSON response from Volley

This might be a simple question, so sorry for that. I'm trying to develop a radio app for my internet radio station. I'm using JSON format for the requests (Example JSON) to get information from my station. For example the "title" tag. I want to get this information.
My first try:
JSONObject data = response.getJSONObject("data");
songname.setText(data.getString("title"));
But the problem is that I cannot get this information. What can I do? Thanks in advance.
As your JSON do like this
JSONObject josnOBJ = new JSONObject(response);
JSONArray jArray = josnOBJ.getJSONArray("data");
JSONObject jsonData = null;
String title = null;
for (int i=0; i < jArray.length(); i++)
{
try {
jsonData = jArray.getJSONObject(i);
title= jsonData .optString("title");
} catch (JSONException e) {
// Oops
}
}
songname.setText(title);
You could use some generic JSON parsers instead of manual work. Eg: https://github.com/bajicdusko/AndroidJsonProvider
Just create model class regarding your json content. Check examples in README on github url.
Hope i could help.
You can use GSON library in case you have lot of values to fetch from JSON ,that would take care of everything for you.

How to check JSON is empty in 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();
}

Parsing json response from google direction api

I'm trying to parse the JSON response from google direction api in my android program. This is the request link bellow. I'm skipping the JSON response here because its too long and simply clicking on the link will show it.
http://maps.googleapis.com/maps/api/directions/json?origin=Windsor&destination=Leamington&sensor=false&avoid=highways&mode=walking
My code for parsing the response :
try {
JSONObject responseObject = (JSONObject) new JSONTokener(responseString).nextValue();
this.responseString = responseObject.getString("status") ;
JSONArray routesArray = responseObject.getJSONArray("routes");
JSONObject route = routesArray.getJSONObject(0);
JSONArray legs ;
JSONObject leg ;
JSONArray steps ;
JSONObject dist;
Integer distance ;
if(route.has("legs")) {
legs = route.getJSONArray("legs");
leg = legs.getJSONObject(0) ;
steps = leg.getJSONArray("steps"); // EDIT : I had somehow missed this line before when copying the code from IDE to the website
int nsteps = steps.length() ;
for(int i=0;i<nsteps;i++) {
JSONObject step = steps.getJSONObject(i);
if(step.has("distance")) {
dist = (JSONObject) step.get("distance");// throws exception
//I would like to take the distance value and do something with it
//if(dist.has("value"))
// distance = (Integer) dist.get("value") ;
}
}
}
else
this.responseString = "not found" ;
} catch ( Exception e) {
e.printStackTrace() ;
}
This throws an exception (again skipping because the JSON response is too big. The stack trace shows the entire response string) :
org.json.JSONException: Expected ':' after polyline at character 13837 of {
"routes" : [
{
"bounds" : {
"northeast" : { ....
I have tried using the getJSONObject function instead of get, but I get the same exception.
dist = step.getJSONObject("distance");
Can anyone please help me by pointing out what am I missing here ? I'm not very familiar with parsin JSON on android yet, so it's quite likely that I'm making a silly mistake somewhere. Thanks.
Another similar post on this site, but not quite the same : JSON parsing of Google Maps API in Android App
As you aren't so familiar, i'd suggest parsing JSON using Gson, esp for complex responses. The case would suit better in your case.
I have used Gson for parsing responses from Google Maps API, Places API and more...
You may be better off using Gson to parse, map data and your model classes. Eg.:
Gson gson = new Gson();
ModelClass modelClass= new ModelClass(); //or ArrayList<ModelClass>
modelClass= gson.fromJson(responseContent,ModelClass.class);
//where responseContent is your jsonString
Log.i("Web service response", ""+modelClass.toString());
https://code.google.com/p/google-gson/
For Naming discrepancies(according to the variables in webservice), can use annotations like
#SerializedName. (So no need to use Serializable)
You can use a for-each loop and verify or operate the data from the model classes.
for(Modelclass object: modelClass.getList()) {
}
http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
How does the Java 'for each' loop work?
Also, use a for-each instead of for(;;) where ever possible.
Check these:
Parsing data with gson from google places
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
How to parse google places json
I am working on the same API right now, thought this would also help, for the model classes:
Displaying multiple routes using Directions API in Android
Try this..
steps = leg.getJSONArray("steps");
int nsteps = steps.length() ;
for(int i=0;i<nsteps;i++) {
if(steps.has("distance")) {
JSONObject new_onj = steps.getJSONObject(i);
dist = new_onj.getJSONObject("distance");
if(dist.has("value"))
distance = (Integer) dist.get("value");
}
}
Your for loop never sets a value for step - are you missing a line
step = steps.getJSONObject(i);
at the top of your for loop?

Retrieve value from JSON responce

I am writing an android application and currently i am getting a JSON reply:
{"Error":"User already exists"}
this is an example of the messages that i get returned
the part that i am after is : "User already exists" and i need to parse it.
The message is currently stored in a string so i would need to convert this to a JSONArray to then convert it to a JSONOject to then be able to call the getString().
what would be the best way to do this?
this may Helps You
String Respones= "{\"Error\":\"User already exists\"}";
try {
JSONObject jobj = new JSONObject(Respones);
String strError = jobj.getString("Error");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I think you can do it directly with JSONTokener and JSONObject if you want ot use default andoid tools.
If you want better, look into the Jackson lib, it's very powerful, open source, kind of standard:
Android JSON Jackson Tutorial
Try this code
JSONArray jsonArray = new JSONArray(ResponseString);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String result = jsonObject.getString("Error").toString().trim();
}

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.

Categories

Resources