【问题标题】:Swift - Parse array in nested JSON Object not workingSwift - 嵌套 JSON 对象中的解析数组不起作用
【发布时间】:2026-01-06 15:45:01
【问题描述】:
let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [.allowFragments])
        if let responseJSON = responseJSON as? [String:Any] {
            if let tJsonObj = xResponse["d"] as? [[String:Any]] {
               // not working here...
            }
        }

tJsonObj 变量没有得到我的 json 数组内容。 我的 json 看起来像这样:

{"d": "[{\"title\":\"xxx\",\"timestamp\":\"2017-10-16 23:53:40\"},{\"title\":\"Mein Test iPhone 7\",\"timestamp\":\"2017-10-17 18:16:24\"}]"}

希望有人能提供帮助 - 谢谢!

【问题讨论】:

标签: ios json swift parsing dictionary


【解决方案1】:

d 的值是另一个 JSON 字符串。你需要使用两次JSONSerialization

do {
  if let responseJSON = try JSONSerialization.jsonObject(with: data) as? [String:Any],
     let tJsonObj = responseJSON["d"] as? String {
        if let innerJSON = try JSONSerialization.jsonObject(with: Data(tJsonObj.utf8)) as? [[String:Any]] { 
           for item in innerJSON {
              print(item)
           }
        }
  }
} catch {
  print(error)
}

【讨论】:

    【解决方案2】:

    d 的内部 JSON 看起来被转义了。有效的 JSON 应该类似于:

    {"d": "[{"title":"xxx","timestamp":"2017-10-16 23:53:40"},...
    

    您的 JSON 来自哪里?

    【讨论】:

    • 来自我服务器的 JSON。对象是用 JavaScriptSerializer 创建的。我确定 JSON 是有效的。