Json在字典中解析数组

时间:2018-05-15 14:03:00

标签: json swift parsing

我在我的应用程序中使用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()
}

我的问题是如何解析&#34; RegisterNumber&#34;,&#34; Title&#34; ..&#34; CustomerList&#34;?它是一个拥有成员的数组。但是我无法在我的函数中解析它。

3 个答案:

答案 0 :(得分:2)

您需要注明的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"
        }
    }
}

答案 1 :(得分:1)

Filename

答案 2 :(得分:1)

最好将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)
        }

    }

获取customerList:

 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()
    }