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

如何编写对应Swift中[[String: String]]类型的JSON表示?

Swift Codable 结构体与JSON匹配问题解析

误解澄清

你当前提供的JSON,其results字段的结构完全匹配你定义的let results: [[String: String]]类型,不存在不匹配的问题。

类型对应说明

Swift的类型语法规则:

  • [String: String]代表单个键值对字典
  • [[String: String]]代表由字典组成的数组

你给出的JSON中:

"results":[
  { "name": "Name1", "result": "Result1" },
  { "name": "Name2", "result": "Result2" },
  { "name": "Name3", "result": "Result3" }
]
  • 外层的[]对应Swift的数组结构
  • 数组内的每个{...}都是[String: String]类型的字典
    因此整个results字段的类型就是[[String: String]],和结构体定义完全一致。

你误以为该JSON对应[String](字符串数组)是错误的——[String]对应的JSON应该是类似["value1", "value2"]的纯字符串数组结构,和你当前的字典数组完全不同。

验证代码

你可以通过以下代码直接测试解码逻辑,确认匹配性:

let jsonData = """
{
   "type":"express",
   "results":[
  { "name": "Name1", "result": "Result1" },
  { "name": "Name2", "result": "Result2" },
  { "name": "Name3", "result": "Result3" }
]
 }
""".data(using: .utf8)!

do {
    let decoded = try JSONDecoder().decode(myResults.self, from: jsonData)
    print(decoded.results) // 正常输出字典数组,无解码错误
} catch {
    print(error)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:30:32