21

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. Any help would be greatly appreciated.

2
  • 3
    Which JSONObject class are you using? There are a few...
    – andyb
    Aug 17, 2011 at 21:16
  • Good point, I had assumed it was the org.json classes. Aug 17, 2011 at 21:28

5 Answers 5

20

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"));
1
  • don't work for me. I can't parse array from jsonObject. JSONArray jArray = obj.getJSONArray("list"); will give me a exception. JSONArray list = new JSONArray(iconIds); obj.put("list", list); This works. I can parse array from obj JSONArray jArray = obj.getJSONArray("list");
    – fangzhzh
    Jun 1, 2014 at 15:19
3

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<Data>();

//if List not empty
if (!sList.isEmpty()) {

    //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();
0
2

This is how I do it using Google Gson. I am not sure, if there are a simpler way to do this (with or without an external library).

Type collectionType = new TypeToken<List<Class>>() {
}.getType();

String gsonString = new Gson().toJson(objList, collectionType);
1

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

2
  • Thank you for the suggestion, but I would like to avoid using a serializer at all costs if I can.
    – Grammin
    Aug 17, 2011 at 20:54
  • Okay, since you want to stick with JSONArray and JSONObject, I provided an alternate answer. Aug 17, 2011 at 21:27
1

Just to update this thread, here is how to add a list (as a json array) into JSONObject. Plz substitute YourClass with your class name;

List<YourClass> list = new ArrayList<>();
JSONObject jsonObject = new JSONObject();

org.codehaus.jackson.map.ObjectMapper objectMapper = new 
org.codehaus.jackson.map.ObjectMapper();
org.codehaus.jackson.JsonNode listNode = objectMapper.valueToTree(list);
org.json.JSONArray request = new org.json.JSONArray(listNode.toString());
jsonObject.put("list", request);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.