Android Studio中Kotlin处理GeoJSON的properties数据问题
在Kotlin中处理GeoJSON的Properties
1. 先定义对应的数据类
如果用Gson解析GeoJSON,先定义匹配结构的Kotlin数据类,方便后续操作:
import com.google.gson.annotations.SerializedName data class FeatureCollection( @SerializedName("type") val type: String, @SerializedName("features") val features: List<Feature> ) data class Feature( @SerializedName("type") val type: String, @SerializedName("properties") val properties: Properties, @SerializedName("geometry") val geometry: Any? = null ) // 根据你的GeoJSON实际字段定义Properties,比如包含year、name等 data class Properties( @SerializedName("year") val year: Int, @SerializedName("name") val name: String )
2. 提取year等于2014的对象到列表
假设你已经从API拿到GeoJSON字符串,解析后直接用Kotlin集合操作筛选:
// 解析GeoJSON字符串为FeatureCollection val gson = com.google.gson.Gson() val featureCollection = gson.fromJson(geoJsonString, FeatureCollection::class.java) // 筛选所有year=2014的Feature val year2014Features = featureCollection.features.filter { it.properties.year == 2014 } // 如果只需要Properties对象,可直接提取: val year2014Properties = featureCollection.features.map { it.properties } .filter { it.year == 2014 }
3. 遍历所有Properties
如果Properties是动态键值对(不确定所有字段),可以把properties类型改为Map<String, Any>,这样就能遍历所有键值:
// 修改Feature类的properties定义 data class Feature( @SerializedName("type") val type: String, @SerializedName("properties") val properties: Map<String, Any>, @SerializedName("geometry") val geometry: Any? = null ) // 遍历单个Feature的所有properties val firstFeature = featureCollection.features.first() firstFeature.properties.forEach { (key, value) -> println("属性键:$key,属性值:$value") } // 遍历所有Feature的properties featureCollection.features.forEach { feature -> println("--- 处理当前Feature的属性 ---") feature.properties.forEach { (key, value) -> println("$key: $value") } }
适配原生JSONObject的写法
如果你用原生JSONObject处理(对应你现有能获取单个属性的代码),可以这样实现:
// 筛选year=2014的Properties列表 val jsonObject = JSONObject(geoJsonString) val features = jsonObject.getJSONArray("features") val year2014List = mutableListOf<JSONObject>() for (i in 0 until features.length()) { val feature = features.getJSONObject(i) val props = feature.getJSONObject("properties") if (props.getInt("year") == 2014) { year2014List.add(props) } } // 遍历所有properties for (i in 0 until features.length()) { val feature = features.getJSONObject(i) val props = feature.getJSONObject("properties") val keys = props.keys() while (keys.hasNext()) { val key = keys.next() val value = props.get(key) println("$key: $value") } }
内容的提问来源于stack exchange,提问作者Lolcoman
相关产品推荐
相关产品推荐

