I have a json string and need to create an ArrayList where array values have to be inserted in the index position according with the ID value in the json string. This is an example of the json String:
{"clients":{"1":"Client 1","2":"Client 2","3":"Client 3"}}
I use this code:
List<String> clientsArray = new ArrayList<String>();
String JsonR = '{"clients":{"1":"Client 1","2":"Client 2","3":"Client 3"}}';
JSONObject lJSONObject = new JSONObject(JsonR);
JSONArray lJSONArray = lJSONObject.getJSONArray("clients");
for (int i = 0; i < lJSONArray.length(); i++)
clientsArray.add(Integer.valueOf(lJSONArray.getJSONObject(i).getString("ID")), lJSONArray.getJSONObject(i).getString("Name"));
}
I get this error:
org.json.JSONException: Value {"1":"Client 1","2":"Client 2","3":"Client 3"} at clients of type org.json.JSONObject cannot be converted to JSONArray
Changed this to get the JSONObject:
JSONObject lJSONObject = new JSONObject(JsonR);
for (int i = 0; i < lJSONObject.length(); i++)
{
clientsArray.add(Integer.valueOf(lJSONObject.getString("ID")), lJSONObject.getString("Name"));
}
In PHP:
$jsonArray = array();
while($Row = $Rows->fetch_array(MYSQLI_ASSOC)) {
$RowsArray = array("ID" => $Row['ID'], "Name" => $Row['Name']);
array_push ($jsonArray, $RowsArray);
}
echo json_encode($jsonArray);
Now I get the error:
org.json.JSONException: Value [{"ID":"1","Name":"Client 1"},{"ID":"2","Name":"Client 2"},{"ID":"3","Name":"Client 3"}] of type org.json.JSONArray cannot be converted to JSONObject
It is not a JSONObject now? Why it say it is a JSONArray?