如何在 Kotlin 中将 JSON 文件中的数据解析为新的 GeoJSON?

问题描述 投票:0回答:1

我对 Kotlin 完全陌生,我正在尝试执行一项任务,但似乎找不到太多文档。我已经在 JavaScript 中编写了需要执行的操作(见下文),但我需要将相同的功能转换为 Kotlin。基本上,我有一个包含坐标的 JSON 文件。我需要提取这些坐标并将它们推入一个全新的 GeoJson 变量中。这是我需要转换的代码,我该怎么做?

let routeTemp = {
    'type': 'FeatureCollection',
    'features': []
}

let geoTemp = {
        'type': 'Feature',
        'properties': {},
        'geometry': {
            'type': 'LineString',
            'coordinates': [],
        }
    };

function jsonToGeo(data) {
    for(track in data.track) {
        let coords = [data.track[track].Lon, data.track[track].Lat];
        geoTemp.geometry['coordinates'].push(coords);
    }
    routeTemp['features'].push(geoTemp);
}
javascript json kotlin parsing geojson
1个回答
0
投票

我最终想出的解决方案......

确保导入此:

import org.json.JSONObject

我将 JSON 定义为全局字符串,然后用它来构造 JSON 对象:

val jsonObject = JSONObject(jsonStr) // convert JSON string into JSON Object

将其包含在 onCreate 函数中:

val coordsLine =  parseJsonL()
val  geoStr = geoTemp(coordsLine)

然后定义这些函数:

// function to parse line coordinates from JSON
fun parseJsonL(): ArrayList<String> {
    // extract tracks as an array from JSON
    val trackArray = jsonObject.getJSONArray("track")
    val coordList = ArrayList<String>()
    // iterate through coordinates for each track, extract as strings, and add to a list
    for (i in 0 until trackArray.length()) {
        val coordsL = trackArray.getJSONObject(i)
        val lon = coordsL.getString("Lon")
        val lat = coordsL.getString("Lat")
        coordList.add("[$lon, $lat]")
    }
    return coordList
}

// function to insert coordinates into GeoJSON template
fun geoTemp(coordsLine: ArrayList<String>): String {
    val geoStr = """
            {
                "type": "FeatureCollection",
                "features": [
                    {
                        "type": "Feature",
                        "properties": {
                            "name": "Sea Wall Route"
                        },
                        "geometry": {
                            "type": "LineString",
                            "coordinates": $coordsLine
                        }
                    }
                ]
            }
        """.trimIndent()
    return geoStr
}

我愿意接受改进此代码的建议,因为我对 Kotlin 还很陌生:)

© www.soinside.com 2019 - 2024. All rights reserved.