简体   繁体   English

如何在Java中读取json文件并创建对象?

[英]How to read json file in java and create objects?

I have a java class named Teacher: 我有一个名为Teacher的Java类:

public class Teacher {
private String _tCode;
private String _tName;
private String[] _teacherLessons;
private int _maxHoursPerDay;
private int _maxHoursPerWeek;

public String get_T_Code(){return this._tCode;}
public String get_T_Name(){return this._tName;}
public String[] get_Teacher_Lessons(){return this._teacherLessons;}
public int    get_Max_Hours_Per_Day(){return this._maxHoursPerDay;}
public int    get_Max_Hours_Per_Week(){return this._maxHoursPerWeek;}

public void set_T_Code(String tCode){this._tCode=tCode;}
public void set_T_Name(String tName){this._tName=tName;}
public void set_Teacher_Lessons(String[] teacherLessons){this._teacherLessons =teacherLessons;}
public void set_Max_Hours_Per_Day(int maxHoursPerDay){this._maxHoursPerDay=maxHoursPerDay;}
public void set_Max_Hours_Per_Week(int maxHoursPerWeek){this._maxHoursPerWeek=maxHoursPerWeek;}

public void teacher (String tCode, String tName, String[] teacherLessons, int maxHoursPerDay, int maxHoursPerWeek){
    this._tCode=tCode;
    this._tName=tName;
    this._teacherLessons=teacherLessons;
    this._maxHoursPerDay=maxHoursPerDay;
    this._maxHoursPerWeek=maxHoursPerWeek;
}
@Override
public String toString(){ return "Code:\t"+this._tCode+"\nName:\t"+this._tName+"\nTeacher Lessons:\t"+this._teacherLessons+
        "\nMax hours per day:\t"+this._maxHoursPerDay+"\nMax hours per week:\t"+this._maxHoursPerWeek;}

}

I want my main class to read from a json file and create Teacher objects but I am not sure what is the best way to write my data into json file. 我希望我的主类从json文件读取并创建Teacher对象,但是我不确定将数据写入json文件的最佳方法是什么。 Here is what I have tried so far: 到目前为止,这是我尝试过的:

[{
    "Teacher Code": "1",
    "Teacher Name": "john",
    "MaxHoursPerDay":5,
    "MaxHoursPerWeek":18,
    "Teacher Lessons": [
       "Maths"
    ]
},
{
    "Teacher Code": "2",
    "Teacher Name": "Bill",
    "MaxHoursPerDay":5,
    "MaxHoursPerWeek":18,
    "Teacher Lessons": [
       "Maths",
       "Physics
    ]
}]

I create objects like this: 我创建这样的对象:

JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\file1.txt"));

  for (Object o : a)
 {
      JSONObject person = (JSONObject) o;

String code= (String) person.get("code");

String name= (String) person.get("name");

int maxHoursD= (int) person.get("MaxHourPerDay");
int maxHoursW= (int) person.get("MaxHourPerWeek");


JSONArray lessons = (JSONArray) person.get("Teacher Lessons");

for (Object c : lessons)
{
  Teacher t = new Teacher(code, name, maxHoursD, maxHoursW, c);
}
}

Is there easier way to read the json data and create objects? 有没有更简单的方法来读取json数据并创建对象? Moreover, is it possible to store json array(Teacher lessons) in a java array as in my constructor? 此外,是否可以像构造函数一样将json数组(教师课程)存储在java数组中?

Google Gson is a pretty good thrid party library that can easily be used along with your code. Google Gson是一个非常不错的第三方库,可以轻松地与您的代码一起使用。 It does exactly what you say you want to do. 它完全按照您说的去做。 Convert objects to JSON and vice versa. 将对象转换为JSON,反之亦然。

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public static void main(String[] args) {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    Teacher teacher = new Teacher("001", "John Doe", 8, 40, "History", "Civics");
    System.out.println("Teacher Object :\n" + gson.toJson(teacher));

    Teacher teacher1 = new Teacher("002", "Ali G", 8, 40, "English Literature", "English Language");
    Teachers teachers = new Teachers(teacher, teacher1);
    System.out.println("Teachers Object :\n" + gson.toJson(teachers));

}

public static class Teachers {
    private Teacher[] teachers;

    public Teachers(Teacher... teachers) {
        this.teachers = teachers;
    }

}

public static class Teacher {
    private String _tCode;
    private String _tName;
    private String[] _teacherLessons;
    private int _maxHoursPerDay;
    private int _maxHoursPerWeek;

    public Teacher(String _tCode, String _tName, int _maxHoursPerDay, int _maxHoursPerWeek,
            String... _teacherLessons) {
        this._tCode = _tCode;
        this._tName = _tName;
        this._teacherLessons = _teacherLessons;
        this._maxHoursPerDay = _maxHoursPerDay;
        this._maxHoursPerWeek = _maxHoursPerWeek;
        this._teacherLessons = _teacherLessons;
    }

}

The results of the above bit of code is as follows : 上面这段代码的结果如下:

Teacher Object :
{
  "_tCode": "001",
  "_tName": "John Doe",
  "_teacherLessons": [
    "History",
    "Civics"
  ],
  "_maxHoursPerDay": 8,
  "_maxHoursPerWeek": 40
}
Teachers Object :
{
  "teachers": [
    {
      "_tCode": "001",
      "_tName": "John Doe",
      "_teacherLessons": [
        "History",
        "Civics"
      ],
      "_maxHoursPerDay": 8,
      "_maxHoursPerWeek": 40
    },
    {
      "_tCode": "002",
      "_tName": "Ali G",
      "_teacherLessons": [
        "English Literature",
        "English Language"
      ],
      "_maxHoursPerDay": 8,
      "_maxHoursPerWeek": 40
    }
  ]
}

The output should tell you exactly how you should structure your JSON in accordance with your model object. 输出应准确告诉您如何根据模型对象构造JSON。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM