I have a class called
class Student {
String name;
String age;
}
I have a method that returns List object like
public List<Student> getList(){
List<Student> li =new ArrayList();
....
li.add(new Student('aaa','12'));
...
return li;
}
I need to convert that list into JSONArray like this
[{"name":"sam","age":"12"},{"name":"sri","age":"5"}]
Can anyone help me to get this?
Create a JSON array by instantiating the JSONArray class and add, elements to the created array using the add() method of the JSONArray class.
JSON defines only two data structures: objects and arrays. An object is a set of name-value pairs, and an array is a list of values.
JSONObject obj = new JSONObject(); List<String> sList = new ArrayList<String>(); sList. add("val1"); sList. add("val2"); obj. put("list", sList);
JsonArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array. A JsonArray object can be created by reading JSON data from an input source or it can be built from scratch using an array builder object.
Using Gson
Library it will be very simple.
From JSON String to ArrayList of Object as:
Type listType =
new TypeToken<ArrayList<Student>>(){}.getType();
ArrayList<Student> yourClassList = new Gson().fromJson(jsonArray, listType);
And to Json from Array List of Object as:
ArrayList<Student> sampleList = new ArrayList<Student>();
String json = new Gson().toJson(sampleList);
The Gson Library is more simple to use than JSONObject
and JSONArray
implementation.
You will have to include the jettison
jar in you project and import the required classes.
JSONObject jObject = new JSONObject();
try
{
JSONArray jArray = new JSONArray();
for (Student student : sudentList)
{
JSONObject studentJSON = new JSONObject();
studentJSON.put("name", student.getName());
studentJSON.put("age", student.getAge());
jArray.put(studentJSON);
}
jObject.put("StudentList", jArray);
} catch (JSONException jse) {
jse.printStacktrace();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With