You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kotlin中反序列化GeoJson FeatureCollection出现异常的问题排查

问题原因及解决方法

这个错误的核心是Gson解析时的类型不匹配——你代码里指定的反序列化目标类型是数组,但实际JSON根节点是FeatureCollection对象,或者缺少必要的适配器导致解析逻辑混乱。具体原因和解决步骤如下:

常见原因

  • 错误指定反序列化目标类型:你可能把FeatureCollection当成了Feature数组/列表来解析(比如用Array<Feature>::class.java或List<Feature>::class.java作为目标类型),但GeoJSON的FeatureCollection本身是一个包含features数组的对象,Gson看到根节点是对象却要解析成数组,就会抛出这个异常。
  • 未注册SpatialK的Gson适配器:io.github.dellisd.spatialk.geojson库的类型(比如FeatureCollection、Point、LineString等)需要对应的GeoJsonAdapterFactory来处理多态几何类型的反序列化,如果没注册这个适配器,Gson无法正确识别FeatureCollection的结构,也可能触发类型匹配错误。

解决步骤

  1. 确保反序列化目标类型为FeatureCollection
    修正代码,明确指定解析为FeatureCollection::class.java,示例:

    import com.google.gson.GsonBuilder
    import io.github.dellisd.spatialk.geojson.FeatureCollection
    import io.github.dellisd.spatialk.geojson.serialization.GeoJsonAdapterFactory
    
    // 初始化Gson并注册适配器
    val gson = GsonBuilder()
        .registerTypeAdapterFactory(GeoJsonAdapterFactory.create())
        .create()
    
    // 从文件读取JSON字符串并解析
    val jsonString = File("your-file.json").readText()
    val featureCollection = gson.fromJson(jsonString, FeatureCollection::class.java)
    
  2. 必须注册GeoJsonAdapterFactory
    这个适配器工厂是SpatialK库专门用来处理GeoJSON多态类型(不同几何对象)的核心组件,没有它,Gson无法正确解析Point、LineString、Polygon等不同类型的geometry字段,进而导致整个FeatureCollection解析失败。

  3. 再次核对JSON结构
    确认你的JSON根节点是标准的FeatureCollection对象,结构如下:

    {
      "type": "FeatureCollection",
      "features": [
        {"type": "Feature", "geometry": {"type": "Point", "coordinates": [100.0, 0.0]}, "properties": {}},
        {"type": "Feature", "geometry": {"type": "LineString", "coordinates": [[100.0, 0.0], [101.0, 1.0]]}, "properties": {}},
        {"type": "Feature", "geometry": {"type": "Polygon", "coordinates": [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]]]}, "properties": {}}
      ]
    }
    

内容的提问来源于stack exchange,提问作者mekoda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 05:12:41