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

使用Klaxon解析嵌套数组遇阻:features子数组properties解析失败

解决Klaxon解析features/[Number]/properties子数组的问题

看起来你卡在了Klaxon对嵌套JSON结构的解析上,核心问题出在你用了Array<Any?>来接收features数组——Klaxon没法自动推断Any类型对应的JSON结构,自然解析不了里面的properties子对象/子数组。下面给你一套可行的解决方案:

1. 定义匹配JSON结构的数据类

首先得把JSON里的嵌套结构对应成具体的Kotlin数据类,不能用模糊的Any。假设你的JSON结构大概是这样的:

{
  "type": "FeatureCollection",
  "totalFeatures": 2,
  "features": [
    {
      "type": "Feature",
      "properties": { /* 或者是一个数组,比如 ["xxx", "yyy"] */ }
    }
  ]
}

那你需要创建对应的数据类:

如果properties是对象:

// 最外层的根对象
data class Haltestelle(
    val type: String?,
    val totalFeatures: Int?,
    val features: Array<Feature?>?
)

// 每个feature的结构
data class Feature(
    val type: String?,
    val properties: Properties? // 对应properties子对象
)

// properties的具体结构,根据你的JSON字段调整
data class Properties(
    val name: String?,
    val id: Int?
    // 补充properties里的其他字段
)

如果properties是子数组:

如果你的properties是数组(比如字符串数组或对象数组),调整Feature类的字段类型:

data class Feature(
    val type: String?,
    val properties: Array<String?>? // 字符串数组的情况
    // 对象数组的话:val properties: Array<PropItem?>?
)

// 若为对象数组,定义对应的数据类
data class PropItem(
    val key: String?,
    val value: String?
)

2. 用Klaxon解析完整JSON

现在用具体的数据类解析,就能正确拿到properties里的内容了:

fun main(args: Array<String>) {
    val jsonContent = // 你的JSON文件内容,或从文件读取的字符串
    val klaxon = Klaxon()
    val haltestelle = klaxon.parse<Haltestelle>(jsonContent)
    
    // 正常访问properties数据
    haltestelle?.features?.forEach { feature ->
        feature?.properties?.let { props ->
            // 处理props内容,比如打印字段
            println(props.name)
        }
    }
}

3. 排查之前的问题

你之前提取properties原始字符串单独解析失败,大概率是因为:

  • 提取的JSON片段格式有误(比如缺失括号、引号)
  • 单独解析时仍未使用对应的数据类,还是依赖模糊的Any类型

注意事项

  • 确保数据类字段名和JSON键完全一致,不一致时可以用@Json(name = "xxx")注解做映射
  • 建议用List代替Array(Klaxon完全支持),避免数组的equals/hashCode问题,比如把Array<Feature?>改成List<Feature?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 03:56:03