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.
You could use a JSON serializer/deserializer like flexjson to do the conversion for you.
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);
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();
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>>() {
} // end new
.getType();
String gsonString =
new Gson().toJson(objList, collectionType);
Source: Stackoverflow.com