使用 google-gson 解析 JSON

Parsing JSON with google-gson

来自服务器的答案

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

如何正确读取对象 "lessons",并将其添加到列表中?

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

其他人也一样

使用包装器对象,您可以直接将其读取为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());
    }

}