JSONArray getting error - java

org.json.JSONException: Value [{"id":"98747406","name":"adam","surname":"hfdd","age":"2","latitude":"54.2118","longitude":"16.1876","origin":"koszalin","destination":"sian\u00f3w","ride_id":"262243421","date":"2017-05-25 18:13:00"}] at jaPassengers of type java.lang.String cannot be converted to JSONArray
Have anyone idea what cause this error? It occur when I try getJSONArray from server output e.g.:
output:
{"iActualJoinRequests":"4","jaPassengers":"[{\"id\":\"98747406\",\"name\":\"adam\",\"surname\":\"hfdd\",\"age\":\"2\",\"latitude\":\"54.2113448\",\"longitude\":\"16.1876282\",\"origin\":\"koszalin\",\"destination\":\"sian\u00f3w\",\"ride_id\":\"262243421\",\"date\":\"2017-05-25
18:13:00\"}]"}
JSONObject joOutput = new JSONObject(output);
JSONArray jaPassengers = joOutput.getJSONArray("jaPassengers");
EDIT: Problem solved, solution in comment.

If you used a json parser, the error would become pretty clear:
"jaPassengers" : "[{\"id\":\"98747406\",\"name\":\"adam\",\"surname\":\"hfdd\",\"age\":\"2\",\"latitude\":\"54.2113448\",\"longitude\":\"16.1876282\",\"origin\":\"koszalin\",\"destination\":\"sian\u00f3w\",\"ride_id\":\"262243421\",\"date\":\"2017-05-25 18:13:00\"}]"
Your array is actually encoded as a string.
To parse this, first fetch it as a string, then parse the resulting string as a JSONArray:
JSONObject joOutput = new JSONObject(output);
String makeShiftArray = joOutput.getString("jaPassengers");
JSONArray jaPassengers = new JSONArray(makeShiftArray);
It would be better to fix this on the server side if possible

Matt Clark, like you advised I'm trying to fix problem on server side. Code:
$aOutput = array('iActualJoinRequests' => $iActualJoinRequests, 'jaPassengers' => $aPassengers);
$joOutput = json_encode($aOutput, JSON_FORCE_OBJECT);
echo $joOutput;
cause error in java when I try to get JSONArray jaPassengers, but:
$aOutput = array('iActualJoinRequests' => $iActualJoinRequests, 'jaPassengers' => '');
$joOutput = json_encode($aOutput, JSON_FORCE_OBJECT);
$joOutput = json_decode($joOutput);
$joOutput -> jaPassengers = $aPassengers;
$joOutput = json_encode($joOutput);
echo $joOutput;
works :)
Problem solved.

Related

java org.json not supporting special characters like \uf4f8 ,\uf389\uf60d \u2026 emojis)

I have java string like below and I am trying to convert to JSONArray using org.json library.
String content = "[{ \"message\":\"This year\\u2019s #SexiestManAlive goes to #chrisevans \\uf389\\uf60d \\u2026they did this one for us \\uf979\\n(\\uf4f8: #mschwartzphoto x #people )\"}]"
JSONArray jsonArray = new JSONArray(content);
When I am converting this to JSONArray some extends emojis are not converting (\uf4f8 ,\uf389\uf60d \u2026". )
it looks like this after converting this msg to jsonarray
"This year’s #SexiestManAlive goes to #chrisevans  …they did this one for us 凉\n(: #mschwartzphoto x #people )"
How can we handle this  ? please need help on this.
For Reference:: actually text message in API looks like this
This year’s #SexiestManAlive goes to #chrisevans 🎉😍 …they did this one for us 🥹
(📸: #mschwartzphoto x #people )

org.json.JSONException: JSONObject["minutes"] not found

This is my JSON object and I am trying to access the minutes from this JSON object but unable to access it, I have also tried writing some code, can anyone please help.
{"summary":"B.Com; LL.B.(Hons.) 5-Year integrated-MIBCBT802R01","recurrence":["RRULE:FREQ=DAILY;COUNT=1"],"reminders":{"overrides":[{"method":"email","minutes":1440}],"useDefault":"false"},"attendees":["qatest1#dc01.tcs-itontap.com"],"start":{"dateTime":"2022-10-24T08:40:00+05:30","timeZone":"India+5:30"},"description":"Lecture scheduled for Subject:Down Stream Processing Lab II and Activity: Practical","location":"India","end":{"dateTime":"2022-10-24T09:30:00+05:30","timeZone":"India+5:30"},"id":2300036}
```String remMinutes = new org.json.JSONObject(new org.json.JSONObject(jsonFromSolJSON.getJSONObject("reminders")).getJSONArray("overrides").getJSONObject(0)).getInt("minutes")```
Err - JSONError:: org.json.JSONException: JSONObject["minutes"] not found.
This could be one of the solution
var jsonObject = new JSONObject(json);
var result = jsonObject.getJSONObject("reminders").getJSONArray("overrides");
var minutes = result.getJSONObject(0).get("minutes");

How to correctly generate Json without Backslashes

Problem:
I get json with backslashes as response from a GET Request
#RequestMapping(value = "repuve/recibe_captcha", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
like this:
{"mensaje":"Proceso ejecutado correctamente.","folio":"1652989601959","resultado":"{\"idSalida\":1,\"descSalida\":\"Proceso Correcto\",\"data\":[.....]}"}
When expected Result is like this:
{"mensaje":"Proceso ejecutado correctamente.","folio":"1652989601959","resultado":"{"idSalida":1,"descSalida":"Proceso Correcto","data":[.....]}"}
(The data array has a b64 image).
This is how json is created:
JSONObject object = new JSONObject();
JSONArray jArray = new JSONArray();
object.put("idSalida", 1);
object.put("descSalida", "Proceso Correcto");
jArray.put(captcha);
object.put("data", jArray);
I've tried some answers from StackOverflow using replace() but none of them seems to work for me.
Is there another way to remove the backslashes and get the correct json format delivered to front?
Thank you.
Any JSON generating framework should actually escape the nested quotation marks. If you expect the string to look differently, you will have write code that assembles that JSONary string the way you want.

JSON parsing No value

Im not sure whats the error behind this, but im getting an error saying
org.json.JSONException: No value for
http://starstrakph.s3.amazonaws.com/12/avatars/1386757806.jpg
My JSON are as follows
{"id":"12","display_name":"Anne","screen_name":"Anne Curtis","avatar":"http:\/\/starstrakph.s3.amazonaws.com\/12\/avatars\/1386757806.jpg","avatar_source":"http:\/\/www.balita.com\/filipino-superstar-anne-curtis-katulong-ng-pechanga-resort-casino-sa-pagdiriwang-ng-araw-ng-kasarinlan-ng-pilipinas\/"}
And my codes are:
JSONObject userObj = new JSONObject(result);
cFeeds.SetPostScreenName(userObj.getString("screen_name"));
String avatar = userObj.getString(userObj.optString("avatar"));
cFeeds.SetAvatar(avatar);
Should I use JSON array for this? is there any wrong on my code or am i missing something?
Thanks in advance
The problem is that you are using the value of the json object (which is a json String) named avatar as the name of another json object which obviously doesn't exist.
String avatar = userObj.getString(userObj.optString("avatar"));
It seems you just want the value of avatar, so just get it
String avatar = userObj.optString("avatar");

When trying to retrieve JSONObject out of JSONArray is returning null?

Im trying to do the following:
UserFunctions uf = new UserFunctions();
JSONArray json = uf.getAllFreebies();
System.out.println(json + "blah1"); //Here im able to retrieve the whole JSONArray.
try{
System.out.println("1");
for (int i = 1; i <json.length(); i++) {
System.out.println("2");
jo = json.optJSONObject(i); //Im getting null value here
System.out.println(jo + "blah2"); //Here im getting null
...}
Im printing out my JSONArray using following lines.
JSONArray json = uf.getAllFreebies();
System.out.println(json + "blah1");
Now on the following lines when i tried to retrieve the JSONObject from the JSONArray and tried to print it out,it prints out "null" instead of the JSONObject at the particular index.
jo = json.optJSONObject(i);
System.out.println(jo + "blah2");
Can anyone pls tell me what am i doing wrong?I mean how can i get a null for JSONOBject when my JSONArray is not null?
Thank You.
Following is my JSONArray logcat:
05-31 21:02:57.156: I/System.out(318): [["viking","Art","Potrait","Potrait","Good","im giving out potrait 7325697","176 Fiat Ave","Iselin","New Jersey","USA","08830","2012-05-27"],["n00b","Books","Novels","Novels","Good","Im giving out novels 7325697","b9 maa krupa","petlad","Gujarat","India","388450","2012-05-27"],["n00b","Computers","laptop","laptop giveaway","Good","Im giving out laptop if you are interested than pls call on 7325697","B9 Ma Krupa","Petlad","Gujarat","India","388450","2012-05-27"],["mista","Cameras & Photos","Camera","Camera GiveAway","Very good","im giving out camera .its kodak .pls email me on mista#gmail.com","Mista Lee elm street","seoul","Korea","South Korea","ha8 9sd","2012-05-27"],["panda","Gaming Consoles","XBOX","XBOX 360","Very Good","Im giving out xbox 360.if you are interested please email me on panda#gmail.com","435 Carmen Rd,","Buffalo","New York","USA","14226","2012-05-27"],["viking","Cameras & Photos","Camera","Kodak Camera","Good","Kodak Camera giveaway.Pls call on 732397","","Iselin","New Jersey","USA","08830","2012-05-28"],["viking","Books","Novels","Novel GA","Good","Novel give away.call on 7325697.","","Iselin","New Jersey","USA","08830","2012-05-28"],["viking","Automotive","Car","Car GiveAway","Good","Im giving out car.if you are interested pls call 7323697.","176 Fiat Ave","Iselin","New Jersey","USA","08830","2012-05-29"],["viking","Collectibles","Medallions","Medallion GA","Very Good","Im giving out medallion.if inetrested pls call 732697","176 Fiat Ave,","Iselin","New Jersey","USA","08830","2012-05-29"],["viking","Clothing & Accessories","cloths","cloths giveaway","Good","im giving out cloths if you are interested pls call on 735697","176 Fiat Ave,","Iselin","New jersey","USA","08830","2012-05-29"],["viking","Books","Novel","Novel GA","Good","pls call 735697","435 carmen rd","buffalo","ny","usa","14226","2012-05-29"],["viking","Books","TextBook","CHemistry 101","GOod","pls call 735697","176 fiat ave","iselin","new jersey","usa","08830","2012-05-29"],["mista","Books","Notebook","Notbook","Good","im giving out notebbok if you are interested pls call 48374288423","elm street","seaoul","na","South Korea","jfjafjk","2012-05-29"]]blah1
logcat output when trying to print out JSONOBject at index i
05-31 21:02:57.156: I/System.out(318): nullblah2
The JSON [[...], [...], [...]] does not contain JSON-objects, but it does have some JSON-arrays.
Thus optJSONObject finds a JSON-array (where it expected a JSON-object) and returns null because it is of the incorrect type. (opt is short for optional.)
Use optJSONArray (note Array and not Object). Alternatively, use getJSONArray, which will throw a JSONException on failure.
Happy coding.
Note that JSON keeps a strict distinction between Objects, Arrays, and the various Values. The concept of an Array being a special (sub)kind of Object (in the JSON sense) exists in JavaScript but does not necessarily extend to other JSON implementations. For instance, the JSONArray class has no relationship with the JSONObject class.

Categories

Resources