Java Gson类型适配器';即使字段设置为不使用Expose进行序列化,仍会调用的write方法 问题

Java Gson类型适配器';即使字段设置为不使用Expose进行序列化,仍会调用的write方法 问题,java,gson,Java,Gson,如果存在TypeAdapter,则Expose注释似乎被忽略。WatusiTypeAdapter的write方法仍然被调用,但是@Expose(serialize=true)意味着它不应该被调用。也许您的想法是应该将该决定委托给TypeAdapter,但这会降低类型适配器的可重用性 问题 这是预期的行为还是错误?状态 除非您构建com.google.gson.gson 使用com.google.gson.GsonBuilder并调用 com.google.gson.GsonBuilder.exc

如果存在
TypeAdapter
,则
Expose
注释似乎被忽略。
WatusiTypeAdapter
write
方法仍然被调用,但是
@Expose(serialize=true)
意味着它不应该被调用。也许您的想法是应该将该决定委托给
TypeAdapter
,但这会降低类型适配器的可重用性

问题 这是预期的行为还是错误?

状态

除非您构建
com.google.gson.gson
使用
com.google.gson.GsonBuilder
并调用
com.google.gson.GsonBuilder.excludeFieldsWithoutExposeAnnotation()
方法

就拿这个例子来说

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

注释,您的
serialize
设置为
true
,因此将调用
write
来序列化字段。另外,我假设您使用的是
excludeFieldsWithoutExposeAnnotation
@SotiriosDelimanolis感谢您捕捉到了这一点。这只是我问题中的一个错误。不,我没有使用不带exposeannotation的
excludefields
。也许这就是问题所在。让我试试看,虽然这需要一些时间,因为我有很多字段。不确定我是如何在文档中遗漏了这些,但我很高兴我做到了。这个答案希望对未来的Gson学习者有用。
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;
    }
}
{}