Gson TypeAdapter的write方法即使设置字段不使用Expose序列化依然会被调用
Gson TypeAdapter's write method is still called even if the field is set not to be serialized using Expose
问题
@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 a com.google.gson.GsonBuilder
and invoke
com.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;
}
}
这将产生
{}
换句话说,write
没有被调用。
这意味着您要公开的所有字段都必须使用 @Expose
注释。
问题
@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;
}
}
这将产生
{}
换句话说,write
没有被调用。
这意味着您要公开的所有字段都必须使用 @Expose
注释。