我有一个类似的Java类:
public class Sclass {
private Student student;
private Teacher teacher;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
}
public class Teacher {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
我想在休息服务中使用Sclass
,因此想要一个json,请提供帮助。
答案 0 :(得分:0)
使用gson
的示例:
Student student = new Student();
student.setName("Student 1");
student.setAge(18);
Teacher teacher = new Teacher();
teacher.setName("Teacher 1");
Sclass sclass = new Sclass();
sclass.setStudent(student);
sclass.setTeacher(teacher);
Gson gson = new Gson();
String json = gson.toJson(sclass);
System.out.println(json);
输出:
{"student":{"name":"Student 1","age":18},"teacher":{"name":"Teacher 1"}}