简体   繁体   English

如何在Swift 4中解析具有字典和数组的JSON?

[英]How to parse a JSON that has dictionaries and arrays in Swift 4?

I need some help on parsing a JSON in Swift 4, I already know how to do it with a simple JSON like this one: 我需要一些帮助解析Swift 4中的JSON,我已经知道如何使用像这样的简单JSON:

{"numNotif":1,"numTqClose":7,"reply":3}

But now I have to parse another JSON that is so huge, it has this structure: https://textuploader.com/dnx8f 但现在我必须解析另一个如此巨大的JSON,它有这样的结构: https//textuploader.com/dnx8f

And this is how I parse a simple JSON but it is not working in this case 这就是我解析一个简单的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()
}

Well, so I would like to use the same code or a similar one in order to parse a JSON that has dictionaries "{}" and arrays "[]" before the values, so in fact I want to get the value of issueId, CategoryStr and so on, but I do not have any idea about how to do it. 好吧,所以我想使用相同的代码或类似的代码来解析在值之前有字典“{}”和数组“[]”的JSON,所以实际上我想得到issueId的值, CategoryStr等,但我不知道如何做到这一点。

Also, I would need to save these values in an array (each value in each field), will it be possible? 另外,我需要将这些值保存在一个数组中(每个字段中的每个值),是否可以?

Thank you in advance! 先感谢您!

You can create ToDoList struct which contains closeDtoList, openDtoList structs as params. 您可以创建包含closeDtoList的ToDoList结构,将openDtoList结构创建为params。 The structure would look like below. 结构如下所示。 The IssueId type is not clear from the json, change it to match the requirement. 从json中不清楚IssueId类型,将其更改为符合要求。

import Foundation

struct ToDoList: Decodable {
    let closeDtoList, openDtoList: [DtoList]
}

struct DtoList: Decodable {
    let issueID: IssueID
    let issueStr, categoryStr: String
    let hasImg: Bool
    let tasksID: IssueID
    let userAssign, userStart: Int

    enum CodingKeys: String, CodingKey {
        case issueID = "issueId"
        case issueStr
        case categoryStr = "CategoryStr"
        case hasImg
        case tasksID = "tasksId"
        case userAssign, userStart
    }
}

struct IssueID: Decodable {

    let id: Int?

    enum CondingKeys: String, CodingKey {
        case id = "id" //replace this with correct id value
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CondingKeys.self)
        if let issueId = try? container.decodeIfPresent(Int.self, forKey: .id) {
            self.id = issueId
        } else {
            self.id = nil
        }
    }
}

All you need to do is to parse the JSON according to your structure. 您需要做的就是根据您的结构解析JSON。 For example: 例如:

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 is what you get from your URLSession call. data是您从URLSession调用中获得的data Basically you cast the JSON object to whatever structure you know that it has. 基本上,您将JSON对象强制转换为您知道的任何结构。 In above example I parse responseObj as a Dictionary then I retrieve closeDtoList key's value from this dictionary as Array of Dictionaries and from the first element of that array (which is a dictionary) I get issueStr key's value which is a String . 在上面的示例中,我将responseObj解析为Dictionary然后closeDtoList Dictionary检索closeDtoList键的值作为字典Array of Dictionaries并从该数组的第一个元素(这是一个字典)中获取issueStr键的值,即String

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

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