【问题标题】:Json parse array in dictionaryJson解析字典中的数组
【发布时间】:2018-05-15 14:02:59
【问题描述】:

我在我的应用程序中使用 json api。它可以检查公司是否使用电子发票。我有一个这样的json数据:

{
        "ErrorStatus": null,
        "Result": {
            "CustomerList": [
                {
                    "RegisterNumber": "6320036072",
                    "Title": "VATAN BİLGİSAYAR SANAYİ VE TİCARET ANONİM ŞİRKETİ",
                    "Alias": "urn:mail:defaultpk@vatanbilgisayar.com",
                    "Type": "Özel",
                    "FirstCreationTime": "2014-01-01T05:35:20",
                    "AliasCreationTime": "2014-01-01T05:35:20"
                }
            ],
            "ISEInvoiceCustomer": true
        }  }

我使用该功能获取 json 数据:

func getClientQuery(authorization:String) {

    let url = NSURL(string: URLCustomerCheck+strRegisterNumber)
    let request = NSMutableURLRequest(url: url! as URL)
    request.httpMethod = "GET"

    request.addValue(authorization, forHTTPHeaderField: "Authorization")

    let task = URLSession.shared.dataTask(with: request as URLRequest) { data,response,error in


        if error != nil {
            let alert = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
            let okButton = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
            alert.addAction(okButton)
            self.present(alert, animated: true, completion: nil)
        } else {

            if data != nil {

                do {

                    let jSONResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String,AnyObject>

                    DispatchQueue.main.async {

                        print(jSONResult)

                        let result = jSONResult["Result"] as! [String:AnyObject]


                        //let customerList = result["CustomerList"] as! [[String:AnyObject]] 



                        let ISEInvoiceCustomer = String(describing: result["ISEInvoiceCustomer"])


                        self._lblISEinvoiceCustomer.text = " \(ISEInvoiceCustomer) "

                    }
                } catch {

                }
            }
        }
    }
    task.resume()
}

我的问题是如何解析“CustomerList”中的“RegisterNumber”、“Title”..?这是一个有成员的数组。但是我无法在我的函数中解析它。

【问题讨论】:

    标签: json swift parsing


    【解决方案1】:

    需要您注释掉的customerList 行。然后迭代该数组并从每个字典中提取您想要的任何值。

    在使用 JSON 时,您确实应该避免使用 as! 或任何其他强制解包。您不希望您的应用在获取意外数据时崩溃。

    永远不要使用String(describing:) 来创建您将向用户显示的值。结果不适合显示。它仅用于调试目的。

    if let jSONResult = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:Any]
        DispatchQueue.main.async {
            print(jSONResult)
    
            if let result = jSONResult["Result"] as? [String:AnyObject],
               let customerList = result["CustomerList"] as? [[String:Any]] {
                for customer in customList {
                    let registrationNumber = customer["RegisterNumber"]
                    // and any others you need
                }
    
                let ISEInvoiceCustomer = result["ISEInvoiceCustomer"] as? Bool ?? false
                self._lblISEinvoiceCustomer.text = ISEInvoiceCustomer) ? "Yes" : "No"
            }
        }
    }
    

    【讨论】:

    • customerList 行正在工作。但例如,我无法解析该数据的成员;让 RegisterNumber = String(描述:customerList["RegisterNumber"]) -> 它不起作用。我想解析 customerList 的成员。
    【解决方案2】:

    最好将 json 映射到 Model ,这变得很容易使用 Codable

     import Foundation
        struct Client: Codable {
            let errorStatus: ErrorStatus?
            let result: Result
    
            enum CodingKeys: String, CodingKey {
                case errorStatus = "ErrorStatus"
                case result = "Result"
            }
        }
    
        struct ErrorStatus: Codable {
        }
    
        struct Result: Codable {
            let customerList: [CustomerList]
            let iseInvoiceCustomer: Bool
    
            enum CodingKeys: String, CodingKey {
                case customerList = "CustomerList"
                case iseInvoiceCustomer = "ISEInvoiceCustomer"
            }
        }
        struct CustomerList: Codable {
            let registerNumber, title, alias, type: String
            let firstCreationTime, aliasCreationTime: String
    
            enum CodingKeys: String, CodingKey {
                case registerNumber = "RegisterNumber"
                case title = "Title"
                case alias = "Alias"
                case type = "Type"
                case firstCreationTime = "FirstCreationTime"
                case aliasCreationTime = "AliasCreationTime"
            }
        }
        // MARK: Convenience initializers
    
        extension Client {
            init(data: Data) throws {
                self = try JSONDecoder().decode(Client.self, from: data)
            }
    
            init(_ json: String, using encoding: String.Encoding = .utf8) throws {
                guard let data = json.data(using: encoding) else {
                    throw NSError(domain: "JSONDecoding", code: 0, userInfo: nil)
                }
                try self.init(data: data)
            }
    
        }
    

    获取客户列表:

     func getClientQuery(authorization:String) {
    
            let url = NSURL(string: URLCustomerCheck+strRegisterNumber)
            let request = NSMutableURLRequest(url: url! as URL)
            request.httpMethod = "GET"
    
            request.addValue(authorization, forHTTPHeaderField: "Authorization")
    
            let task = URLSession.shared.dataTask(with: request as URLRequest) { data,response,error in
    
    
                if error != nil {
                    let alert = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
                    let okButton = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
                    alert.addAction(okButton)
                    self.present(alert, animated: true, completion: nil)
                } else {
    
                    if data != nil {
                        if let client  = try? Client.init(data: data){
                            client.result.customerList.forEach { (customer) in
                                print(customer.registerNumber)
                            }
                        }
    
                    }
                }
            }
            task.resume()
        }
    

    【讨论】:

      【解决方案3】:
      let data = resultData
         do {
             guard let JSONResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String : AnyObject],
                 let resultObject = JSONResult["Result"] as? [String : AnyObject],
                 let customerList = resultObject["CustomerList"] as? [Anyobject] 
                 else { return }
      
                 // Loop the array of objects
                 for object in customerList {
                      let registerNumber = object["RegisterNumber"] as? String
                      let title = object["Title"] as? String
                      let alias = object["Alias"] as? String
                      let type = object["Type"] as? String
                      let firstCreationTime = object["FirstCreationTime"] as? String // Or as a DateObject
                      let aliasCreationTime = object["AliasCreationTime"] as? String // Or as a DateObject
                 }
      
                 let isEInvoiceCustomer = resultObject["ISEInvoiceCustomer"] as? Bool
      
      } catch {
           print(error)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多