2

我想为类定义自己的序列化和反序列化方法Student,所以我扩展TypeAdapter并覆盖了它的方法,但现在反序列化不起作用。为什么会发生这种情况?

public class GSONFormat {

@Test
public void run()
{
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(Student.class, new StudentAdapter());
    Gson gson = builder.create();
    Student s = new Student();
    s.setAge(11);
    s.setName("hiway");
    System.out.println(gson.toJson(s));
    String str = "{\"age\":11,\"name\":\"hiway\"}";
    s = gson.fromJson(str, Student.class);
    System.out.println(s);
}
}

class Student{
    private int age;
    private String name;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

class StudentAdapter extends TypeAdapter<Student>
{

    @Override
    public void write(JsonWriter out, Student s) throws IOException {
        out.beginObject();
        out.name("age");
        out.value(s.getAge());
        out.name("name");
        out.value(s.getName());
        out.endObject();
    }

    @Override
    public Student read(JsonReader in) throws IOException {
        in.beginObject();
        Student s = new Student();
        s.setAge(in.nextInt());
        s.setName(in.nextString());
        in.endObject();
        return s;
    }
}
4

1 回答 1

2

正如 Matt Ball 所评论的那样,如果您根本没有很好的理由,那么编写您的类型适配器根本不是一个好主意。如果删除此行:

builder.registerTypeAdapter(Student.class, new StudentAdapter());

您的解析将不费吹灰之力。但是,您可能有兴趣进一步了解您可以使用类型适配器做什么。所以我给你一个可能的实现。请记住,如果您的类Student变得更复杂,编写自己的类型适配器可能会很困难。最好让Gson自己做。无论如何,这里有一些东西可以修补您的代码(在 Java7 下编译,如果您使用较低版本,请使用链进行更改switchif

class StudentAdapter extends TypeAdapter<Student>
{

    @Override
    public void write(JsonWriter out, Student s) throws IOException {
        out.beginObject();
        out.name("age");
        out.value(s.getAge());
        out.name("name");
        out.value(s.getName());
        out.endObject();
    }

    @Override
    public Student read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
            return null;
          }


        in.beginObject();
        Student s = new Student();
        while (in.peek() == JsonToken.NAME){
            String str = in.nextName();
            fillField(in, s, str);
        }


        in.endObject();
        return s;
    }

    private void fillField(JsonReader in, Student s, String str)
            throws IOException {
        switch(str){
            case "age": s.setAge(in.nextInt());
            break;
            case "name": s.setName(in.nextString());
            break;
        }
    }
}
于 2013-10-02T06:19:23.000 回答