问题
@JsonAdapter(WatusiTypeAdapter.class)
@Expose(serialize = false, deserialize = true)
private Watusi watusi;
如果存在TypeAdapter,则Expose注释似乎被忽略. WatusiTypeAdapter的write方法仍然被调用,但是@Expose(serialize = true)表示不应该这样.也许是您应该将该决定委托给TypeAdapter,但这会使类型适配器的可重用性大大降低.
问题
这是预期的行为还是错误?
解决方法:
This annotation has no effect unless you build
com.google.gson.Gson
with acom.google.gson.GsonBuilder
and invokecom.google.gson.GsonBuilder.excludeFieldsWithoutExposeAnnotation()
method.
举个例子
public class Example {
public static void main(String[] args) {
Example example = new Example();
example.other = new Other();
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
System.out.println(gson.toJson(example));
}
@JsonAdapter(value = OtherAdapter.class)
@Expose(serialize = true)
private Other other;
}
class Other {
}
class OtherAdapter extends TypeAdapter<Other> {
@Override
public void write(JsonWriter out, Other value) throws IOException {
System.out.println("hey");
out.endObject();
}
@Override
public Other read(JsonReader in) throws IOException {
// TODO Auto-generated method stub
return null;
}
}
这将产生
{}
换句话说,未调用写入.
这意味着您要公开的所有字段都必须使用@Expose进行注释.