How to Create JSONArray for a List

后端 未结 7 2005
南旧
南旧 2020-12-30 00:47

I have a class called

class Student {
   String name;
   String age;
}

I have a method that returns List object like

publi         


        
相关标签:
7条回答
  • 2020-12-30 01:29

    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();
    }
    
    0 讨论(0)
  • 2020-12-30 01:30

    I think you need not download the jettison jar file.

    Using JSONArray and JSONObject you can easily convert that list into JSON object like @Juniad answer

    0 讨论(0)
  • 2020-12-30 01:31

    When you want to map Object to json directly or want to convert json to object, you can use GSON library . this will give you more flexibility and control.

    Download link - http://code.google.com/p/google-gson/

    Tutorial link - http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

    0 讨论(0)
  • 2020-12-30 01:36

    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.

    0 讨论(0)
  • 2020-12-30 01:36

    try gson: Serializing-and-Deserializing-Generic-Types

    0 讨论(0)
  • 2020-12-30 01:38

    Create JSONArray like below.

    JSONArray jsArray = new JSONArray(arrayList);

    0 讨论(0)
提交回复
热议问题