2011-06-22 45 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上發佈了四個不同的問題和答案鏈接(一些代碼示例)。

相關問題