【问题标题】:Why does Gson serializes runtime type in list, not specified compile-time type?为什么 Gson 在列表中序列化运行时类型,而不是指定编译时类型?
【发布时间】:2015-08-01 00:32:28
【问题描述】:

为什么 Gson 在序列化时似乎忽略了嵌套的泛型类型声明?

我试图让 Gson 使用我指定的编译时类型,而不是列表中对象的运行时类型。我也在为A.java 使用抽象超类,但下面的示例也有同样的问题。

public class A {
    public String foo;
}

public class B extends A {
    public String bar;
}

public static void main( String[] args ) {
    Gson gson = new Gson();

    B b = new B();
    b.foo = "foo";
    b.bar = "bar";

    List<A> list = new ArrayList<A>();
    list.add(b);

    System.out.println(gson.toJson(b, new TypeToken<A>(){}.getType()));
    System.out.println(gson.toJson(b, new TypeToken<B>(){}.getType()));

    System.out.println(gson.toJson(list, new TypeToken<List<A>>(){}.getType()));
    System.out.println(gson.toJson(list, new TypeToken<List<B>>(){}.getType()));
}

输出:

{"foo":"foo"}
{"bar":"bar","foo":"foo"}
[{"bar":"bar","foo":"foo"}]
[{"bar":"bar","foo":"foo"}]

预期:

{"foo":"foo"}
{"bar":"bar","foo":"foo"}
[{"foo":"foo"}]
[{"bar":"bar","foo":"foo"}]

【问题讨论】:

  • 欢迎来到 Stack Overflow!我只是想让你知道,对于你在这里的第一篇文章来说,这是一个很好的问题。希望以后多多参与!

标签: java json generics types gson


【解决方案1】:

这是因为 Gson 默认是如何序列化集合的。

为什么会这样?

如果您不关心原因而只想修复,请滚动到底部。

Gson 的默认 CollectionTypeAdapterFactory 将它的元素类型适配器包装在称为 TypeAdapterRuntimeTypeWrapper 的东西中。选择合适的适配器时,它使用the following priorities:

// Order of preference for choosing type adapters
// First preference: a type adapter registered for the runtime type
// Second preference: a type adapter registered for the declared type
// Third preference: reflective type adapter for the runtime type (if it is a sub class of the declared type)
// Fourth preference: reflective type adapter for the declared type

在这种情况下,第三个首选项是 B 的适配器,第四个首选项是 A 的适配器。使用默认序列化程序时这是无法避免的,因为有 no conditional in the CollectionTypeAdapterFactory

public Adapter(Gson context, Type elementType,
    TypeAdapter<E> elementTypeAdapter,
    ObjectConstructor<? extends Collection<E>> constructor) {
  this.elementTypeAdapter =
      new TypeAdapterRuntimeTypeWrapper<E>(context, elementTypeAdapter, elementType);
  this.constructor = constructor;
}

当不使用 CollectionTypeAdapterFactory 时,此包装器不存在,这就是为什么它不会在前两个示例中发生。

tl;dr 好的,那我该如何解决呢?

解决此问题的唯一方法是注册一个自定义序列化程序。A 编写一个就可以解决问题,在您的用例中:

public class ATypeAdapter extends TypeAdapter<A> {
  public A read(JsonReader reader) throws IOException {
    if (reader.peek() == JsonToken.NULL) {
      reader.nextNull();
      return null;
    }
    reader.beginObject();
    String name = reader.nextName();
    if(!"foo".equals(name)) throw new JsonSyntaxException("Expected field named foo");
    A a = new A();
    a.foo = reader.nextString();
    reader.endObject();
    return a;
  }

  public void write(JsonWriter writer, A value) throws IOException {
    if (value == null) {
      writer.nullValue();
      return;
    }
    writer.beginObject();
    writer.name("foo");
    writer.value(value.foo);
    writer.endObject();
  }
}

那么,如果你这样做:

public static void main( String[] args ) {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(new TypeToken<A>(){}.getType(), new ATypeAdapter());
    Gson gson = builder.create();

    B b = new B();
    b.foo = "foo";
    b.bar = "bar";

    List<A> list = new ArrayList<A>();
    list.add(b);

    System.out.println(gson.toJson(b, new TypeToken<A>(){}.getType()));
    System.out.println(gson.toJson(b, new TypeToken<B>(){}.getType()));

    System.out.println(gson.toJson(list, new TypeToken<List<A>>(){}.getType()));
    System.out.println(gson.toJson(list, new TypeToken<List<B>>(){}.getType()));
}

你得到了预期的输出:

{"foo":"foo"}
{"bar":"bar","foo":"foo"}
[{"foo":"foo"}]
[{"bar":"bar","foo":"foo"}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    • 1970-01-01
    相关资源
    最近更新 更多