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