2013-02-19 216 views
1

我試圖反序列化一個包含GeoJSON字符串的JSON字符串。使用Gson反序列化JSON數據

point: { 
    type: "Point", 
    coordinates: [ 
     7.779259, 
     52.21864 
    ] 
} 

我要創建的對象的類型

com.vividsolutions.jts.geom.Point 

的我們使用,因爲使用的空間數據的POSTGIS數據庫的這一類。不幸的是,該類沒有非參數構造函數,這是必需的。但不知何故,它也實現了CoordinateSequence CoordinateSequence,它們都沒有非參數構造函數。每當我試圖反序列化傳入的JSON字符串,我得到一個錯誤

java.lang.RuntimeException: Unable to invoke no-args constructor for 
interface com.vividsolutions.jts.geom.CoordinateSequence. 
Register an InstanceCreator with Gson for this type may fix this problem. 

我試圖創造的CoordinateSequence的接口的InstanceCreator下面的例子here,但沒有成功。 也子類Point沒有帶來答案,因爲問題出在CoordinateSequence的已用界面上。

我會感謝任何幫助或提示,導致我的解決方案。

+0

你可以使用默認的構造函數來擴展com.vividsolutions.jts.geom.Point類,並且序列化/反序列化它們嗎? – 2013-02-19 16:38:47

+0

嗨Alexey, 感謝您的評論。我已經試過擴展點。請參閱下面的評論。 – 2013-02-20 10:22:25

回答

1

我們使用Custom JsonDeserializer解決了它。當然,這只是一個快速和骯髒的解決方案。應該檢查其他類型和錯誤。但是這應該給出一個想法。

public class GeometryDeserializer implements JsonDeserializer<Geometry> { 

@Override 
public Geometry deserialize(JsonElement json, Type typeofT, 
     JsonDeserializationContext context) throws JsonParseException { 

    String type = json.getAsJsonObject().get("type").toString(); 

    JsonArray coordinates = json.getAsJsonObject().getAsJsonArray("coordinates"); 

    GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null); 
    Coordinate coord = new Coordinate(coordinates.get(0).getAsDouble(), coordinates.get(1).getAsDouble()); 
    Geometry point = geometryFactory.createPoint(coord); 


    return point; 
} 
} 
0

我假設這個班級來自你不能改變的圖書館。你有沒有試過對類進行子類化,並在你的子類中放置一個無參數構造函數來協助序列化過程?我之前已經取得了一些成功。

// .... content I cant change. 
public class LibraryPOJOClass { 
    public LibraryPOJOClass(final int id) { 
    // ... 
    } 
} 

public class MyLibraryPojoClass extends LibraryPOJOClass { 
    MyLibraryPojoClass() { 
    super(0); // I will change this later, with reflection if need be. 
    } 
} 
+0

嗨羅伯特, 感謝您的回答。但不幸的是我已經嘗試了子類。看起來不是Point本身就是問題,但更多的是我無法觸及的CoordinateSequence的已用界面。 – 2013-02-20 10:21:50

0

就做服務器端:

SELECT ST_GeomFromGeoJSON('{"type":"Point","coordinates":[7.779259,52.21864]}'); 

注:在這個問題提供的例子看起來比The GeoJSON Format Specification略有不同。

+0

嗨邁克, 這將工作,如果Point對象是你想要堅持的唯一對象。但是Point被嵌入在另一個對象中。 – 2013-02-20 16:52:54