javajsonclasslist

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


I have a List<class> that I would like to convert into a JSON object and then traverse the data out of the JSON object.

If this were just a List<String> I could just do something like:

JSONObject obj = new JSONObject();
List<String> sList = new ArrayList<String>();
sList.add("val1");
sList.add("val2");

obj.put("list", sList);

Then I could traverse the list like:

JSONArray jArray = obj.getJSONArray("list");
for (int ii = 0; ii < jArray.size(); ii++)
    System.out.println(jArray.getString(ii));

The problem with using the class is that I need to have access to data within each class element of my List<class> and I don't know how to encode that / traverse it into JSON.


Solution

  • 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"));