我需要一些关于在 Swift 4 中解析 JSON 的帮助,我已经知道如何使用像这样的简单 JSON 来完成它:
{"numNotif":1,"numTqClose":7,"reply":3}
但现在我必须解析另一个非常大的 JSON,它具有以下结构:https://textuploader.com/dnx8f
这就是我解析简单 JSON 的方式,但在这种情况下不起作用
import UIKit
struct closeDtoList: Decodable {
let CategoryStr:String
}
class test: UIViewCOntroller {
super.viewDidLoad() {
let urlJSON = "http://www.example.net/site/gitAll"
guard let url = URL(string: urlJSON) else {return}
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let data = data else {return}
guard error == nil else {return}
do {
let closeDto = try JSONDecoder().decode(closeDtoList.self, from: data)
print(closeDto.CategoryStr)
} catch let error {
print(error)
}.resume()
}
好吧,所以我想使用相同的代码或类似的代码来解析在值之前具有字典“{}”和数组“[]”的 JSON,所以实际上我想获得值issueId、CategoryStr 等等,但我不知道该怎么做。
此外,我需要将这些值保存在一个数组中(每个字段中的每个值),这可能吗?
提前致谢!
最佳答案
您需要做的就是根据您的结构解析 JSON。例如:
if let responseObj = try? JSONSerialization.jsonObject(with: data) {
if let responseData = responseObj as? [String: Any] { // Parse dictionary
if let closeDtoList = responseData["closeDtoList"] as? [[String: Any]] {// Parse an array containing dictionaries
if closeDtoList.count > 0 {
// You should use a loop here but I'm just doing this way to show an example
if let issueStr = closeDtoList[0]["issueStr"] as? String { // Parse a string from dictionary
}
}
}
}
}
data
是您从 URLSession 调用中获得的内容。基本上,您将 JSON 对象转换为您知道它具有的任何结构。在上面的示例中,我将 responseObj 解析为 Dictionary
然后我从该字典中检索 closeDtoList
键的值作为 Array of Dictionaries
并从该字典的第一个元素中检索数组(这是一个字典)我得到 issueStr
键的值,它是一个 String
。
关于json - 如何在 Swift 4 中解析包含字典和数组的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52854244/