Search code examples
jsonkotlingsondeserializationgeojson

Error deserializing FeatureCollection in Kotlin


I'm trying to deserialize a GeoJson FeatureCollection contained in a file (.json extension), with contents:

{
  "type": "FeatureCollection",
  "features": [
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [
          102.0,
          0.5
        ]
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "LineString",
        "coordinates": [
          [
            102.0,
            0.0
          ],
          [
            103.0,
            1.0
          ],
          [
            104.0,
            0.0
          ],
          [
            105.0,
            1.0
          ]
        ]
      }
    },
    {
      "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
            ]
          ]
        ]
      }
    }
  ]
}

The code I have for this task is this:

    fun deserializeGeoJsonFromFile(filePath: String): FeatureCollection? {
        val gson = Gson()
        val typeToken = object : TypeToken<FeatureCollection>() {}.type

        return try {
            val fileContent = File(filePath).readText()
            gson.fromJson(fileContent, typeToken)
        } catch (e: Exception) {
            println("Error deserializing GeoJSON from file: ${e.message}")
            null
        }
    }

I'm using the FeatureCollection from io.github.dellisd.spatialk.geojson.

I get an error:

Error deserializing GeoJSON from file: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

To me, seems that the parser was expecting an array somewhere, but got something else instead. However, I checked the JSON and it's not malformed. Any ideas about what's happening?


Solution

  • I found the problem: in a nutshell, I was using Gson (which is built in context of general JSON) to deserialize SpatialK-specific types; I guess the error makes sense, as Gson has no obligation to understand domain specific objects.

    I solved by replacing:

    gson.fromJson(fileContent, typeToken)
    

    with (note that it's SpatialK + kotlinx.serialization now):

    Json.decodeFromString(FeatureCollection.serializer(), fileContent)