Java 用googlegson解析JSON
答案来自服务器Java 用googlegson解析JSON,java,json,gson,Java,Json,Gson,答案来自服务器 { "error":false, "lessons":[ { "id":1, "discipline":"??????????", "type":"LECTURE", "comment":"no comments" }, { "id":2, "discipline":"???. ??", "type":"LECTURE", "comment":"no comments" } ] } 如何正确阅读对象“课程”,并添
{
"error":false,
"lessons":[
{
"id":1,
"discipline":"??????????",
"type":"LECTURE",
"comment":"no comments"
},
{
"id":2,
"discipline":"???. ??",
"type":"LECTURE",
"comment":"no comments"
}
]
}
如何正确阅读对象“课程”,并添加到列表中
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(数据,wrapper.class)代码>
import java.util.List;
导入com.google.gson.gson;
类包装器{
布尔误差;
列出经验教训;
//接球手和接球手
}
课堂{
字符串id;
弦乐学科;
字符串类型;
字符串注释;
//接球手和接球手
}
公共类GsonSample{
公共静态void main(字符串[]args){
字符串数据=“{\'error\':false,\'lessons\':[{\'id\':1,\'production\':\”、\'type\':“讲座”、\'comment\':“无评论”}、{\'id\':2,\'production\':“?”、\'type\':“讲座”、\'comment\':“无评论”};
Wrapper obj=new Gson().fromJson(数据,Wrapper.class);
System.out.println(obj.getLessons());
}
}
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());
}
}