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

Swift如何解码OpenWeatherMap地理编码API中路径以0开头的JSON

解决OpenWeatherMap地理编码API的JSON解码问题

首先明确:你拿到的JSON是数组类型(外层是[]),不是单个对象,所以不需要用PositionData结构体包裹,也完全没必要用CodingKey处理"0"——那个"0"其实是数组的索引,不是JSON对象的键。

正确的结构体定义

先定义对应单个城市位置的结构体,包含你需要的字段:

struct CityLocation: Decodable {
    let name: String
    let lat: Double
    let lon: Double
    let country: String
    let state: String? // state可能为空,用可选型
    let localNames: [String: String]?
    
    // 处理local_names的蛇形命名转驼峰
    enum CodingKeys: String, CodingKey {
        case name, lat, lon, country, state
        case localNames = "local_names"
    }
}

正确的解码代码

直接把JSON数据解码成[CityLocation]类型(城市位置数组),然后取第一个匹配的结果即可:

do {
    let decodedLocations = try decoder.decode([CityLocation].self, from: positionData)
    // 检查数组不为空再取值,避免越界
    if let firstLocation = decodedLocations.first {
        print(firstLocation.lat)
        print(firstLocation.lon)
        // 其他字段按需使用
    } else {
        print("未找到匹配的城市数据")
    }
} catch {
    print("JSON解码错误: \(error)")
}

原代码问题说明

  1. 你错误地把数组当成了带"0"键的对象,定义的PositionData和CodingKeys完全不符合返回的JSON结构。
  2. 调用时试图访问decodedData.0,但你的PositionData里定义的属性是zer0(字母o而非数字0),所以编译器报错找不到成员"0"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:33:01