提问人:Brianna Drew 提问时间:10/4/2023 更新时间:11/1/2023 访问量:50
如何在 Kotlin 中将 JSON 文件中的数据解析为新的 GeoJSON?
How can I parse data from a JSON file into a new GeoJSON in Kotlin?
问:
我是 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);
}
答:
0赞
Brianna Drew
11/1/2023
#1
我最终想出的解决方案......
确保导入以下内容:
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 :)非常陌生
评论
0赞
Tommy
11/2/2023
您好@BriannaDrew感谢您的回复,有人实际上在这里回答了我的问题:stackoverflow.com/questions/77378653/......您知道如何下载已创建的GeoJSON文件吗?
评论