user2272143
user2272143

Reputation: 469

Convert Json String to ArrayList

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?

Upvotes: 0

Views: 74

Answers (1)

Anubis94
Anubis94

Reputation: 163

Because this is a JSON Object

{"1":"Client 1","2":"Client 2","3":"Client 3"}

JSON Array should be like this

[{"1":"Client 1","2":"Client 2","3":"Client 3"}]

This is an example for you but this is a wrong JSON Array.

Whats wrong? How to fix?

You are trying to convert JSON objects to JSON Array. And also another problem. Your JSON Object does not contain these objects ID and Name. Need to fix it like this {"clients":[{"id":1,"name":"Client 1"},{"id":2,"name":"Client 2"},{"id":3,"name":"Client 3"}]}

Upvotes: 2

Related Questions