我想为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;
}
}
答案 0 :(得分:2)
正如马特·鲍尔所评论的那样,如果你没有充分理由那么写你的类型适配器并不是一个好主意。如果您删除此行:
builder.registerTypeAdapter(Student.class, new StudentAdapter());
您的解析将毫不费力地工作。但是,您可能有兴趣进一步了解使用类型适配器可以做些什么。所以我给你一个可能的实现。请记住,如果您的班级Student
变得更复杂,那么编写自己的类型适配器可能会很困难。让Gson做自己的工作更好。无论如何,这里是修补你的代码的东西(在Java7下编译,如果你使用较低版本,用switch
链改变if
)。
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;
}
}
}