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

如何从多层嵌套JSON结构中获取Properties结构体的title属性值

问题排查与解决方案
  • 你的代码存在两个可调整点:
    1. 可选值解包后使用错误:你已经通过if let result = results完成了可选值安全解包,但后续遍历仍使用了未解包的results.features,属于不规范的可选值访问。
    2. 模型层级遍历不完整:Features结构体中的properties是[Properties]数组类型,要拿到title属性需要对properties数组做二次遍历。

调整后的完整代码

getJSON(urlString: urlString) { (results: main?) in
    // 安全解包根模型
    guard let mainModel = results else { return }
    // 遍历features数组
    for feature in mainModel.features {
        print(feature.something)
        // 二次遍历当前feature下的properties数组
        for property in feature.properties {
            print(property.title)
        }
    }
}

补充说明

如果你的实际JSON结构中properties对应的是单个对象而非数组,需要先修正模型定义:

struct Features: Decodable{
    let something: String
    // 把数组类型改成单个Properties类型
    let properties: Properties
}

此时不需要二次遍历,直接访问即可:

print(feature.properties.title)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:27:02