Gson處理子類和父類中有相同屬性bean異常處理

Gson 2.0以後序列化和反序列化 子類和父類中具備相同屬性的bean會拋異常「class XXX declares multiple JSON fields named XXX」, 大體的處理方法有: 一、刪除 父類或子類 中重複的屬性 二、用 transient 關鍵字 修飾 子類或父類中不須要序列化的字段 三、爲這個類單獨註冊TypeAdapter 測試代碼以下:ide

Person.class測試

public class Person {
    private String name;
    private String age;
    // ignore getter and setter
}

Student.classui

public class Student extends Person {
    private String name;
    private String score;
    // ignore getter and setter
}

用gson處理student 會跑錯以下code

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;
    }
}

這樣運行就整常了ip

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);
相關文章
相關標籤/搜索