在 Swift 3 中将 JSON 对象解析为 NSArray

Posted

技术标签:

【中文标题】在 Swift 3 中将 JSON 对象解析为 NSArray【英文标题】:Parsing JSON object to NSArray in Swift 3 【发布时间】:2016-10-06 12:09:15 【问题描述】:

在我将项目转换为 swift 3 后,当我尝试将 JSON 对象解析为 NSArray 这是我的代码时出现运行时错误

  let receipt: Data! = try? Data(contentsOf: receiptURL)
    if receipt == nil //NSData(contentsOfURL: receiptURL, options: nil, error: nil)!
        //            validateReceipt(false)
        return
    
    let base64Data: String = receipt.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) as String

    let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last?.path//
    do
        let payload: Dictionary = ["receipt-data" : base64Data as String, "password": sharedSecret as String ]
        let receiptData = try JSONSerialization.data(withJSONObject: payload, options: JSONSerialization.WritingOptions.prettyPrinted)

        let request = NSMutableURLRequest(url: URL(string: serverURL)!, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: 10) // ur website

        request.httpMethod = "POST"

        request.httpBody = receiptData as! Data?
        var response: URLResponse?
        let resultData = try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning: &response)

        do
            let json = try JSONSerialization.jsonObject(with: resultData, options: .mutableLeaves) as? NSDictionary
            let statusCode = (json?.object(forKey: "status") as! NSNumber).intValue

            switch(statusCode)
            case 21000, 21002, 21003, 21004, 21006:
                return
            // break
            case 21005:
                //Server is not available: Save recipt data and try again later
                return
            case 21007:
                validateReceipt(true)
                return

            case 21008:
                validateReceipt(false)
                return

            default:
                break
            
            //print("**********************************")
            //print("json :: ", json )
            //print("**********************************")
            if let parseJSON = json 

                let latest_receipt_info:NSArray = (parseJSON.object(forKey: "receipt") as AnyObject).object(forKey: "in_app") as! NSArray
                //var ms = 0

                //parse the json reponse and add the objects into array
                for i in 0 ..< latest_receipt_info.count 
                    let object:[String: String] = latest_receipt_info.object(at: i) as! [String : String]
                    let strMS = object["expires_date_ms"]
                    let prodId = object["product_id"]
     if(prodId == iAPItems["LifeTime"] || prodId == iAPItems["Remove_Ads"])
                        latestObjectsForEachProduct[prodId!] = object
                    else
                        if let oldTransaction = latestObjectsForEachProduct[prodId!] 
                            let strOldMS = oldTransaction["expires_date_ms"]

                            print("oldTransaction ::  ",prodId, " :: ",strOldMS)
                            if( strMS!.toDouble() > strOldMS!.toDouble() )
                                //latestObject = object
                                latestObjectsForEachProduct[prodId!] = object
                                //ms = str!.toInt()
                            
                        else
                            latestObjectsForEachProduct[prodId!] = object
                        

                    
                

错误出现在这一行

let latest_receipt_info:NSArray = (parseJSON.object(forKey: "receipt") as AnyObject).object(forKey: "in_app") as! NSArray 

我不知道该怎么办,如果有人可以帮忙

请注意,它在 swift 2 上的工作

【问题讨论】:

【参考方案1】:

试试这个代码

让 json = 尝试 JSONSerialization.jsonObject(with: resultData, options: .mutableLeaves) as? NS词典 让 statusCode = (json?.object(forKey: "status") as!NSNumber).intValue

替换这段代码

let json = try JSONSerialization.jsonObject(with: resultData, options: .mutableLeaves) as? [String:AnyObject]
            let statusCode = (json?["status"] as! NSNumber).intValue

让 latest_receipt_info:NSArray = (parseJSON.object(forKey: "receipt") as AnyObject).object(forKey: "in_app") as! NSArray

替换这段代码

let latest_receipt_info:NSArray = parseJSON["receipt"]!["in_app"] as! NSArray

【讨论】:

以上是关于在 Swift 3 中将 JSON 对象解析为 NSArray的主要内容,如果未能解决你的问题,请参考以下文章

在 Swift 中将 Alamofire 结果解析为对象(使用:Alamofire、SwiftyJSON 和 ObjectMapper)

在 Swift 4 中将 Json 对象转换为数组格式

如何在 Swift 中将 Realm 对象转换为 JSON?

如何在 Swift 中将 Firestore FieldValue 解析为日期

在 Scala / Spark 中将 JSON 结构解析为 JSON 对象

如何从解析中的对象中获取 ObjectId 并在 swift 中将其呈现为字符串