2011-06-22 46 views
0

情况Gson,如何为泛型类型编写JsonDeserializer?

我有一个拥有泛型类型的类,它也有一个非零参数构造函数。我不想公开零参数构造函数,因为它可能导致错误的数据。

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)?

CHEERS :)

p.s.我不相信我需要一个JsonSerializer,这应该开箱即用:)

+0

https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Gener should work。 –

+0

你有没有想出一个解决方案? –

回答

0

注意:这个答案是根据问题的第一个版本。编辑和后续问题改变了事情。

p.s.我不相信我需要一个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上发布了四个不同的问题和答案链接(一些代码示例)。

相关问题