2012-05-29 13 views
8

tengo una clase llamadaCómo crear JSONArray para una Lista <Class name>

class Student { 
    String name; 
    String age; 
} 

Tengo un método que devuelve objeto de lista como

public List<Student> getList(){ 

List<Student> li =new ArrayList(); 
.... 

li.add(new Student('aaa','12')); 
... 

return li;  
} 

Necesito convertir esa lista en JSONArray como esto

[{"name":"sam","age":"12"},{"name":"sri","age":"5"}] 

¿Alguien me puede ayudar a conseguir esto? Gracias en Advancee ..

Respuesta

4

Creo que no necesita descargar el archivo jar de jettison.

Usando JSONArray y JSONObject se puede convertir fácilmente en esa lista objeto JSON como @Juniad respuesta

1

JSON-lib es probable que la biblioteca que busca. puede encontrar algunos ejemplos de uso here.

13

Deberá incluir el jar jettison en su proyecto e importar las clases requeridas.

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

+ esta respuesta es segura mi tarde. :) –

12

Usando Gson Biblioteca será muy sencilla.

De JSON cadena a ArrayList de objetos como:

Type listType = 
    new TypeToken<ArrayList<Student>>(){}.getType(); 
ArrayList<Student> yourClassList = new Gson().fromJson(jsonArray, listType); 

Y a JSON de serie de listas de objetos como:

ArrayList<Student> sampleList = new ArrayList<Student>(); 
String json = new Gson().toJson(sampleList); 

La Biblioteca Gson es más fácil de usar que JSONObject y JSONArray aplicación .

+1

salvaste mi tarde ..! gracias, – Suresh

+1

@Suresh eres bienvenido .. :) –

Cuestiones relacionadas