【问题标题】:Gson, How to write a JsonDeserializer for Generic Typed Classes?Gson,如何为泛型类型类编写 JsonDeserializer?
【发布时间】:2011-06-22 11:53:32
【问题描述】:

情况

我有一个包含泛型类型的类,它还有一个非零参数构造函数。我不想公开一个零参数的构造函数,因为它会导致错误的数据。

public class Geometries<T extends AbstractGeometry>{

    private final GeometryType geometryType;
    private Collection<T> geometries;

    public Geometries(Class<T> classOfT) {
        this.geometryType = lookup(classOfT);//strict typing.
    }

}

有几个(已知的和最终的)类可以扩展 AbstractGeometry。

public final Point extends AbstractGeometry{ ....}
public final Polygon extends AbstractGeometry{ ....}

示例 json:

{
    "geometryType" : "point",
    "geometries" : [
        { ...contents differ... hence AbstractGeometry},
        { ...contents differ... hence AbstractGeometry},
        { ...contents differ... hence AbstractGeometry}
    ]
}

问题

如何编写一个 JsonDeserializer 来反序列化通用类型类(例如 Geometires)?

干杯:)

附言我不相信我需要一个 JsonSerializer,这应该是开箱即用的 :)

【问题讨论】:

标签: gson


【解决方案1】:

注意:此答案基于问题的第一个版本。编辑和随后的问题改变了一切。

附言我不相信我需要一个 JsonSerializer,这应该是开箱即用的 :)

根本不是这样。您发布的 JSON 示例与您显然想要绑定和生成的 Java 类结构不匹配。

如果你想要像 Java 这样的 JSON,你肯定需要自定义序列化处理。

JSON 结构是

an object with two elements
    element 1 is a string named "geometryType"
    element 2 is an object named "geometries", with differing elements based on type

Java结构是

an object with two fields
    field 1, named "geometryType", is a complex type GeometryType
    field 2, named "geometries" is a Collection of AbstractGeometry objects

主要区别:

  1. JSON 字符串与 Java 类型 GeometryType 不匹配
  2. JSON 对象与 Java 类型集合不匹配

鉴于此 Java 结构,匹配的 JSON 结构将是

an object with two elements
    element 1, named "geometryType", is a complex object, with elements matching the fields in GeometryType
    element 2, named "geometries", is a collection of objects, where the elements of the different objects in the collection differ based on specific AbstractGeometry types

您确定您发布的内容确实是您想要的吗?我猜应该改变其中一个或两个结构。

关于多态反序列化的任何问题,请注意,该问题已在 StackOverflow.com 上讨论过几次。我在Can I instantiate a superclass and have a particular subclass be instantiated based on the parameters supplied 发布了指向四个不同此类问题和答案的链接(有些带有代码示例)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2020-02-23
    • 2016-10-04
    • 1970-01-01
    相关资源
    最近更新 更多