I have a java class named Teacher:
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. 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? Moreover, is it possible to store json array(Teacher lessons) in a java array as in my constructor?