Gson 2.0之后序列化和反序列化 子类和父类中具有相同属性的bean会抛异常“class XXX declares multiple JSON fields named XXX”, 大致的处理方法有: 1、删除 父类或子类 中重复的属性 2、用 transient 关键字 修饰 子类或父类中不需要序列化的字段 3、为这个类单独注册TypeAdapter 测试代码如下:
Person.class
public class Person {
private String name;
private String age;
// ignore getter and setter
}
Student.class
public class Student extends Person {
private String name;
private String score;
// ignore getter and setter
}
用gson处理student 会跑错如下
String _stu = "{'name':'test','score':'100','age':'20'}";
Gson gson = new GsonBuilder().create();
Student stu = gson.fromJson(_stu, Student.class);
StudentTypeAdapter.class
public class StudentTypeAdapter extends TypeAdapter<Student> {
@Override
public void write(JsonWriter out, Student value) throws IOException {
out.beginObject();
out.name("name").value(value.getName());
out.name("age").value(value.getAge());
out.name("score").value(value.getScore());
out.endObject();
}
@Override
public Student read(JsonReader in) throws IOException {
Student student = new Student();
in.beginObject();
while (in.hasNext()) {
String field = in.nextName();
if ("name".equals(field)) {
student.setName(in.nextString());
} else if ("age".equals(field)) {
student.setName(in.nextString());
} else if ("score".equals(field)) {
student.setScore(in.nextString());
}else{
in.skipValue();
}
}
in.endObject();
return student;
}
}
这样运行就整常了
String _stu = "{'name':'test','score':'100','age':'20'}";
Gson gson = new GsonBuilder().registerTypeAdapter(Student.class, new StudentTypeAdapter()).create();
Student stu = gson.fromJson(_stu, Student.class);