问题
想象一下以下字段:
@JsonAdapter(CustomTypeAdapter.class)
private int field;
反序列化时,CustomTypeAdapter
的read
方法会照常调用,但序列化时, write
方法被完全忽略,内置类型被写出,就像它通常那样。 (如果我使用 Integer
而不是 int
,也会发生同样的事情。)
问题
我在 the documentation 中找不到任何内容这表示这是预期的行为。是吗?或者这是一个错误?
解决方法
我能找到的唯一解决方法是创建一个自定义的“持有人”类型,然后公开它,例如,
@JsonAdapter(CustomTypeAdapter.class)
class CustomType { /* blah blah */ }
private CustomType field;
public int getField() {
return field.getValue();
}
public void setField(int field) {
this.field = new CustomType(field);
}
这可行,但有点麻烦。
最佳答案
虽然我同意它不适用于 int
, 我无法为 Integer
重现它不会的行为在 Gson 2.3.1 中。首先,您必须使用 TypeAdapter<Integer>
(或 TypeAdapterFactory
)而不是 JsonSerializer
.它在 JsonAdapter
中特别说明Javadoc.
The class referenced by this annotation must be either a
TypeAdapter
or aTypeAdapterFactory
. Using the factory interface makes it possible to delegate to the enclosingGson
instance.
然后,类型不会自动装箱,所以如果你想使用注释,该字段必须是Integer
。 .在玩具示例中结合这两个事实(同样,int
将不起作用),我们有:
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
public class JsonAdapterExample {
public static void main(String[] args) {
Gson g = new Gson();
System.out.println(g.toJson(new Car()));
}
public static class Car {
@JsonAdapter(IdAdapter.class)
Integer id = 10;
}
public static class IdAdapter extends TypeAdapter<Integer> {
@Override
public Integer read(JsonReader arg0) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public void write(JsonWriter arg0, Integer arg1) throws IOException {
arg0.beginObject();
arg0.name("id");
arg0.value(String.valueOf(arg1));
arg0.endObject();
}
}
}
输出:
{"id":{"id":"10"}}
如果它不起作用,它将是 10
不是"10"
,并且没有内部对象。
关于java - 为什么在序列化内置类型时会忽略 JsonAdapter 注解?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32469056/