Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create JSONArray for a List<Class name>

Tags:

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?

like image 748
Navamani Samuel Avatar asked May 29 '12 09:05

Navamani Samuel


People also ask

How do you write JSONArray?

Create a JSON array by instantiating the JSONArray class and add, elements to the created array using the add() method of the JSONArray class.

Can a JSON object be a list?

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.

How do I create a list in JSON object?

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

How is JSONArray defined?

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.


2 Answers

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.

like image 158
Mandar Pandit Avatar answered Oct 08 '22 01:10

Mandar Pandit


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();
}
like image 25
JHS Avatar answered Oct 08 '22 01:10

JHS