json - 如何在 Swift 4 中解析包含字典和数组的 JSON?

标签 json swift xcode parsing

我需要一些关于在 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/

相关文章:

iphone - 无论如何要在 iOS 应用程序更新过程中清除 <application_home>/Documents 文件夹吗?

swift - 使用 Swift 3 在两个 Storyboard之间移动时导航栏消失

javascript - 如何使用 Google PageSpeed API 计算网页的总大小?

javascript - 属性未添加到 JS 对象

javascript - 从 json 对象而不是 json 加载 Tensorflowjs

ios - 以编程方式从 UIView 加载 View Controller

python - 如何将 json 转换为 python 类?

ios - 按日期和字符对核心数据属性进行排序

SwiftUI 缩放背景拦截点击

ios - NSObject代替头文件