我有这个架构:
public class Student {
public String name;
public School school;
}
public class School {
public int id;
public String name;
}
public class Data {
public ArrayList<Student> students;
public ArrayList<School> schools;
}
我想用 Gson 序列化 Data 对象,并得到类似的东西:
{ "students": [{
"name":"name1",
"school": "1" //the id of the scool, not its entire Json
}],
"school": [{ //the entire JSON
"id" : "1",
"name": "schoolName"
}]
}
为此,我必须为学生部分使用自定义序列化程序,以便 Gson 只打印学校的 id。但对于学校来说,我必须有普通的序列化器。
我怎样才能只用一个 Gson 对象来完成所有事情?
您可以编写一个自定义序列化程序,如下所示:
public class StudentAdapter implements JsonSerializer<Student> {
@Override
public JsonElement serialize(Student src, Type typeOfSrc,
JsonSerializationContext context) {
JsonObject obj = new JsonObject();
obj.addProperty("name", src.name);
obj.addProperty("school", src.school.id);
return obj;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)