我有一个 json文件,如下所示:
{
"Student" : [
{
"name": "john",
"age": 12
}, {
"name": "jack",
"age": 20
}
]
}
和我的学生班是:
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
我想使用json创建一个名称为“ jack”的Student
实例
我该怎么办?
答案 0 :(得分:2)
制作另一个包含Students
的类List<Student>
。
public class Students {
List<Student> Student;
public List<Student> getStudents() {
return Student;
}
public void setStudent(List<Student> students) {
this.Student=students;
}
}
Gson gson = new Gson();
String jsonString = "Your Json String";
Students student = gson.fromJson(jsonString, Students.class);
答案 1 :(得分:0)
我在解析JSON时使用org.json.simple
库
例子:
excample App.java,
excample Information.java
List<Information> parseInformationObject(JSONArray infoList) {
List<Information> in = new ArrayList<>();
infoList.forEach(emp -> {
JSONObject info = (JSONObject) emp;
String id = info.get("id").toString();
String state = info.get("state").toString();
String type = null;
if (info.get("type") != null) {
type = info.get("type").toString();
}
String host = null;
if (info.get("host") != null) {
host = info.get("host").toString();
}
long timestamp = (long) info.get("timestamp");
in.add(new Information(id, state, type, host, timestamp));
});
return in;
}