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.
Related
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.
{
"Query":"query",
"KMAQuery":"query",
"TotalCount":3,
"Data":[{"CollName":"kmdb_new",
"TotalCount":3,
"Count":3,
"Result":[{"title":"sampletitle",
"director":[{"directorNm":"name1","directorId":"00004544"}],
"nation":"nation1",
"company":"company1",
"genre":"genre1",
"kmdbUrl":"http://www.kmdb.or.kr/vod/vod_basic.asp?nation=K&p_dataid=01040",
"rating":[{"ratingMain":"Y","ratingDate":"19640717","ratingNo":"","ratingGrade":"","releaseDate":"","runtime":""}]]}
Here is my Json Data from OKHttp parsing.
Actually There is many same Result 2~3.
I want to parsing key name "title", "directorNm", "nation", "company", "ratingGrade" and set Model class.
How to parsing multiple Json Object and Array with Gson into Model class?
I'm finally going to use the recyclerview with model class.
If you tell me how to parsing "title" and "directorNm", I can do to rest.
For reference, I am using a AsyncTask, OKHttp, Gson etc.
If you don't understand my question or need code, please comment!
I need your help vigorously.
Here I am sharing the code settting response from Model(Pojo Class)
public void getResponse(JSONObject jsonObject){
try {
JSONObject responseJson = new JSONObject(jsonObject.toString());
JSONArray jsonArray = responseJson.getJSONArray("heroes");
for (int i = 0; i < jsonArray.length(); i++){
//getting the json object of the particular index inside the array
JSONObject jsonObject = jsonArray.getJSONObject(i);
YourPojoClass pojoObject = new YourPojoClass();
pojoObject.setName(jsonObject.getString("name"));
pojoObject.setImageurl(jsonObject.getString("imageurl"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
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.
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
}
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();
}