【问题标题】:How to access element from json object inside a dictionary in swift如何在swift中从字典中的json对象访问元素
【发布时间】:2020-11-03 16:37:52
【问题描述】:

我从服务器获取一个字符串作为 API 调用响应,它是一个编码令牌。我解码令牌并获取此有效负载。我可以将“数据”或“iat”值作为键值对访问,但如何循环抛出并访问“数据”键内的元素?请帮忙。

["iat": 1594655088, "data": 
[{"questionCode":"7a75bf82baea11eabffcfa5fb99b9064","question":"In which country you need to 
visit to explore Petra? ","image":"https://tbbd-flight.s3.ap-southeast- 
1.amazonaws.com/quiz/UihDZXwomcu-d2viNsL7UiewQYiqqpXJ.png","options": 
[{"answerCode":"7a766accbaea11ea8317fa5fb99b9064","answer":"Malaysia "}, 
{"answerCode":"7a766b94baea11eaaf95fa5fb99b9064","answer":"Jordan "}, 
{"answerCode":"7a766c02baea11ea8b10fa5fb99b9064","answer":"Vietnam "}, 
{"answerCode":"7a766c66baea11eaa920fa5fb99b9064","answer":"Australia "}]},

{"questionCode":"8b02bff8baea11ea9882fa5fb99b9064","question":"Worlds one of the most 
luxarious hotel \"Burj Al Arab\"  in which country?","image":"https://tbbd-flight.s3.ap- 
southeast-1.amazonaws.com/quiz/QTKKvpJxhWY7DA-G4bhnOdPoQ02WsR4o.png","options": 
[{"answerCode":"8b036cd2baea11eaaa03fa5fb99b9064","answer":"France"}, 
{"answerCode":"8b036d9abaea11ea8085fa5fb99b9064","answer":"Dubai"}, 
{"answerCode":"8b036e12baea11eabafefa5fb99b9064","answer":"England"}, 
{"answerCode":"8b036e80baea11eabf20fa5fb99b9064","answer":"Canada"}]}
]]

【问题讨论】:

  • 您可以使用 SwiftyJSON 参考:link
  • 添加到目前为止的代码并解释问题
  • @AzimShaikh 当内置 json 支持如此出色时,使用旧的 3rd 方库毫无意义,请查看 Codable

标签: ios json swift dictionary


【解决方案1】:

使用 Codable 使用以下模型解码上述 JSON data

struct Response: Codable {
    let iat: Int
    let data: [Question]
}

struct Question: Codable {
    let questionCode, question: String
    let image: String
    let options: [Option]
}

像这样解析 JSON data

do {
    let response = try JSONDecoder().decode(Response.self, from: data)
    let questions = response.data
    questions.forEach {
        print($0.questionCode)
        //use more fields here...
    }
} catch {
    print(error)
}

【讨论】:

  • 对于我们经常看到的这类问题,我们真的需要另一个答案吗?
  • @PGDev 问题是当我将“数据”放入“让响应 = 尝试 JSONDecoder().decode(Response.self, from: data)”时,它给了我一个错误,即:“无法将“[String : Any]”类型的值转换为预期的参数类型“Data”。我知道如何映射,但在这里无法得到这个错误。抱歉没有在问题上提及。
  • @JoakimDanielson 我不认为即使对同一件事有这么多的答案仍然对 OP 有所帮助。
  • 我的意思是这种低质量的 json 问题,我们看到 OP 没有付出任何努力,只是一些 json 消息,OP 希望我们为其编写正确的代码
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-06
  • 1970-01-01
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多