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