【问题标题】:how to convert a json file to some object calsses如何将 json 文件转换为一些对象类
【发布时间】:2019-04-17 06:23:54
【问题描述】:

我有一个像这样的 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 实例 我该怎么做?

【问题讨论】:

  • 到目前为止您尝试过什么?你用的是什么 JSON 库?
  • 您似乎希望我们为您编写一些代码。虽然许多用户愿意为陷入困境的程序员编写代码,但他们通常只会在发布者已经尝试自己解决问题时提供帮助。展示这项工作的一个好方法是包含您迄今为止编写的代码、示例输入(如果有的话)、预期输出以及您实际获得的输出(控制台输出、回溯等)。您提供的详细信息越多,您可能收到的答案就越多。检查FAQHow to Ask

标签: java json gson


【解决方案1】:

创建另一个类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);

【讨论】:

    【解决方案2】:

    我在解析 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;
        }
    

    【讨论】:

      猜你喜欢
      • 2017-10-25
      • 2014-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-17
      • 2017-12-27
      相关资源
      最近更新 更多