2015-05-29 107 views
0

从服务器附带的答案JSON解析与谷歌,GSON

{ 
"error":false, 
"lessons":[ 
    { 
    "id":1, 
    "discipline":"??????????", 
    "type":"LECTURE", 
    "comment":"no comments" 
}, 
{ 
    "id":2, 
    "discipline":"???. ??", 
    "type":"LECTURE", 
    "comment":"no comments" 
    } 
] 
} 

如何正确读取对象“教训”,并添加到列表?

回答

0

使用一个包装对象,你可以直接把它读作Wrapper obj = new Gson().fromJson(data, Wrapper.class);

import java.util.List; 
import com.google.gson.Gson; 

class Wrapper { 
    boolean error; 
    List<Lesson> lessons; 

    //Getters & Setters 
} 

class Lesson { 
    String id; 
    String discipline; 
    String type; 
    String comment; 

    //Getters & Setters 
} 

public class GsonSample { 

    public static void main(String[] args) { 
     String data = "{\"error\":false,\"lessons\":[{\"id\":1,\"discipline\":\"??????????\",\"type\":\"LECTURE\",\"comment\":\"no comments\"},{\"id\":2,\"discipline\":\"???. ??\",\"type\":\"LECTURE\",\"comment\":\"no comments\"}]}"; 

     Wrapper obj = new Gson().fromJson(data, Wrapper.class); 
     System.out.println(obj.getLessons()); 
    } 

} 
0
JSONArray lessions = response.getJSONArray("lessons"); 
JSONObject obj1 = lessions.getJSONObject(1); // 1 is index of elemet of array 
String id = Obj1.getString("id"); 

而同为他人