Home > Software engineering >  Convert Json String to ArrayList
Convert Json String to ArrayList

Time:09-06

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

CodePudding user response:

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"}]}

  • Related