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

时间:2022-08-26 11:49:38

After i convert my project to swift 3 i had run time error when i try to parsing JSON object to NSArray this my code

我将我的项目转换为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
                        }

                    }
                }

the errors appears on this line

错误出现在这一行

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

i dont know what should i do , if any one can help

我不知道该怎么做,如果有人可以提供帮助的话

Note that on swift 2 its work

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

1 个解决方案

#1


2  

Try this code

试试这个代码

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

让json =尝试JSONSerialization.jsonObject(带:resultData,options:.mutableLeaves)为? NSDictionary允许statusCode =(json?.object(forKey:“status”)为!NSNumber).intValue

to replace this code

替换此代码

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

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

让latest_receipt_info:NSArray =(parseJSON.object(forKey:“receipt”)为AnyObject).object(forKey:“in_app”)as! NSArray的

To replace this code

要替换此代码

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

#1


2  

Try this code

试试这个代码

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

让json =尝试JSONSerialization.jsonObject(带:resultData,options:.mutableLeaves)为? NSDictionary允许statusCode =(json?.object(forKey:“status”)为!NSNumber).intValue

to replace this code

替换此代码

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

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

让latest_receipt_info:NSArray =(parseJSON.object(forKey:“receipt”)为AnyObject).object(forKey:“in_app”)as! NSArray的

To replace this code

要替换此代码

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