如何将json文件转换为某些对象

时间:2019-04-17 06:23:54

标签: java json gson

我有一个 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实例 我该怎么办?

2 个答案:

答案 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.javaexcample 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;
    }