How to put a List<class> into a JSONObject and then read that object? How to put a List<class> into a JSONObject and then read that object? json json

How to put a List<class> into a JSONObject and then read that object?


Call getJSONObject() instead of getString(). That will give you a handle on the JSON object in the array and then you can get the property off of the object from there.

For example, to get the property "value" from a List<SomeClass> where SomeClass has a String getValue() and setValue(String value):

JSONObject obj = new JSONObject();List<SomeClass> sList = new ArrayList<SomeClass>();SomeClass obj1 = new SomeClass();obj1.setValue("val1");sList.add(obj1);SomeClass obj2 = new SomeClass();obj2.setValue("val2");sList.add(obj2);obj.put("list", sList);JSONArray jArray = obj.getJSONArray("list");for(int ii=0; ii < jArray.length(); ii++)  System.out.println(jArray.getJSONObject(ii).getString("value"));


Let us assume that the class is Data with two objects name and dob which are both strings.

Initially, check if the list is empty. Then, add the objects from the list to a JSONArray

JSONArray allDataArray = new JSONArray();List<Data> sList = new ArrayList<String>();    //if List not empty    if (!(sList.size() ==0)) {        //Loop index size()        for(int index = 0; index < sList.size(); index++) {            JSONObject eachData = new JSONObject();            try {                eachData.put("name", sList.get(index).getName());                eachData.put("dob", sList.get(index).getDob());            } catch (JSONException e) {                e.printStackTrace();            }            allDataArray.put(eachData);        }    } else {        //Do something when sList is empty    }

Finally, add the JSONArray to a JSONObject.

JSONObject root = new JSONObject();    try {        root.put("data", allDataArray);    } catch (JSONException e) {        e.printStackTrace();    }

You can further get this data as a String too.

String jsonString = root.toString();


You could use a JSON serializer/deserializer like flexjson to do the conversion for you.