简体   繁体   English

快速循环一个 JSON 响应

[英]Loop through a JSON response in swift

This is a sample of my JSON response这是我的 JSON 响应示例

{
   "dashboard_content":[
      {
         "Subject":"HELLO WORLD",
         "Date":"2022-01-10",
         "Name":"John Wick",
         "Message":"How are you?"
      },
      {
         "Subject":"HELLO you",
         "Date":"2022-05-10",
         "Name":"Sherlock Holmes",
         "Message":"Is this you?"
      }
   ]
}

How can I loop through the JSON Array/Dictionary and print Subject, Date, Name and Message each time?如何循环遍历 JSON 数组/字典并每次打印主题、日期、名称和消息?

A possible solution could look like this:一个可能的解决方案可能如下所示:

let jsonStr = """
{"dashboard_content":[{"Subject":"HELLO WORLD","Date":"2022-01-10","Name":"John Wick", "Message":"How are you?"},{"Subject":"HELLO you","Date":"2022-05-10","Name":"Sherlock Holmes", "Message":"Is this you?"}]}
"""

struct Response: Decodable {
    let dashboard_content: [Content]
    
    struct Content: Decodable {
        let Subject: String
        let Date: String
        let Name: String
        let Message: String
    }
}

if
    let jsonData = jsonStr.data(using: .utf8),
    let response = try? JSONDecoder().decode(Response.self, from: jsonData)
{
    response.dashboard_content.forEach { element in
        print(element.Subject, element.Date, element.Name, element.Message)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM