简体   繁体   中英

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

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

        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

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 {
        let array = try JSONSerialization.jsonObject(with: data) as? [[String : Any]]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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