【问题标题】:Deserializing JSON data using Gson使用 Gson 反序列化 JSON 数据
【发布时间】:2013-02-19 16:33:14
【问题描述】:

我试图反序列化包含 GeoJSON 字符串的 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.

我尝试按照示例here 为CoordinateSequence 的接口创建一个InstanceCreator,但没有成功。 子类化 Point 也没有带来答案,因为问题在于使用的 CoordinateSequence 接口。

我会感谢任何帮助或提示,让我找到解决方案。

【问题讨论】:

  • 你能用你自己的默认构造函数扩展 com.vividsolutions.jts.geom.Point 类,并序列化/反序列化它们吗?
  • 嗨,Alexey,感谢您的评论。我已经尝试过扩展 Point.请在下面查看我的评论。

标签: java json deserialization gson


【解决方案1】:

我们使用自定义 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;
}
}

【讨论】:

    【解决方案2】:

    我假设该类来自您无法更改的库。您是否尝试对类进行子类化并在子类中放置一个无参数构造函数只是为了帮助序列化过程?我以前做过,并取得了一些成功。

    // .... 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. 
      }
    }
    

    【讨论】:

    • 您好罗伯特,感谢您的回答。但不幸的是,我已经尝试过子类化。似乎不是Point本身的问题,而是我无法触摸的CoordinateSequence的使用接口。
    【解决方案3】:

    做服务器端:

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

    注意:问题中提供的示例与The GeoJSON Format Specification 略有不同。

    【讨论】:

    • 嗨,迈克,如果 Point 对象是您想要保留的唯一对象,这将起作用。但是 Point 嵌入在另一个对象中。
    猜你喜欢
    • 2017-03-30
    • 2017-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    相关资源
    最近更新 更多