简体   繁体   English

如何在Swift 3中将来自服务器的响应从字符串转换为数组?

[英]How to convert the response got from a server from string to array in swift 3?

Here I got the response after posting parameters successfully and I need to retrieve it back but the problem I got stuck here that I had saved the data in responseString and it is storing in the form of string and when I try to retrieve it and saving in an array unable to save can anyone help me how to save and the data is in below format 在这里,在成功发布参数之后,我得到了响应,我需要将其取回,但是我遇到的问题是,我已经将数据保存在responseString并且它以字符串形式存储,并且当我尝试检索并保存时无法保存的数组有人可以帮助我如何保存并且数据格式如下

Here is the server response 这是服务器响应

[
  {
    "carrier_code": "flatrate",
    "method_code": "flatrate",
    "carrier_title": "Flat Rate",
    "method_title": "Fixed",
    "amount": 0,
    "base_amount": 0,
    "available": true,
    "error_message": "",
    "price_excl_tax": 0,
    "price_incl_tax": 0
  },
  {
    "carrier_code": "tablerate",
    "method_code": "bestway",
    "carrier_title": "Best Way",
    "method_title": "Table Rate",
    "amount": 0,
    "base_amount": 0,
    "available": true,
    "error_message": "",
    "price_excl_tax": 0,
    "price_incl_tax": 0
  }
]

Here is the json function to post parameters 这是发布参数的json函数

        func shippingmethodURL(shippingMethodAPI:String) {
        let url = NSURL(string: shippingMethodAPI)
        var request = URLRequest(url: url! as URL)
        request.httpMethod = "POST"
        print(shippingMethodAPI)
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let addtoCartVC = storyboard.instantiateViewController(withIdentifier: "checkout") as! CheckoutViewController
        let parameters : [String: Any] = ["address":
            [ "region": "California",
                "region_code": "CA",
                "region_id": "12",
                "country_id": "US",
                "company": "Test",
                "telephone": "9492162752",
                "postcode": "43",
                "city": "Chennai",
                "firstname": "gdfgdgdfg",
                "lastname": "dgdfgdfgg",
                "email": "sfdsfsdf@gmail.com",
                "prefix": "",
                "sameAsBilling": 1,
                "street": ["Dsfdsfsd dfdsfdsf dsfsfdsfsf sdfsfdsfsdfC"]]]
        print(parameters)
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)

        } catch let error {
            print(error.localizedDescription)
        }
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        print(request)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            guard let data = data, error == nil else {
                print("error=\(String(describing: error))")
                return
            }

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }
            let responseString = String(data: data, encoding: .utf8)
            print("responseString = \(responseString!)")

            let status = (response as! HTTPURLResponse).statusCode
            self.keyStatusCode = status
            print(status)
            let array = responseString
        }
        task.resume()
    }

You are converting Data to String However it is Array You need to use JSONSerialization class to achive this 您正在将Data转换为String但是它是Array您需要使用JSONSerialization类来实现这一点

You have to replace this code 您必须替换此代码

 let responseString = String(data: data, encoding: .utf8)

with

let array = try JSONSerialization.jsonObject(with: data!) as? [[String : Any]]

EDIT 编辑

You need put it in do try catch block like this 您需要将其放入do try catch

   do {
        let array = try JSONSerialization.jsonObject(with: data) as? [[String : Any]]

    } catch {
        print("Exception occured \(error))")
    }

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

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