I
I
Ilya Fedorov2017-05-15 09:57:52
JSON
Ilya Fedorov, 2017-05-15 09:57:52

How to process JSON data received with Alamofire in Swift3?

Two libraries are connected: Alamofire 4.4 and SwiftyJSON.
Using the example from the documentation, I received data from the server in utf8:

Alamofire.request(getCitiesURL).responseData { response in
     debugPrint("All Response Info: \(response)")    
     if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) {
           print("Data: \(utf8Text)")
     }
}

"133","name":"Sochi"}] Please help me. How to extract properties (id and name) from a json string so that they can be written into arrays? For example using SwiftyJSON. Ps When I try to access the property, I get an error - Cannot subscript a value of type String with an index of type String
if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) {
        print("Data: \(utf8Text["id"])")
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
ManWithBear, 2017-05-15
@ManWithBear

Invitation to Hogwarts

A
andrew8712, 2017-05-16
@andrew8712

That's right, because `utf8Text` is a constant of type String, you can't access it like this: utf8Text["id"].
You need to cast response.value to dictionary [String: Any] or, even simpler, use responseJSON instead of responseData:

Alamofire.request("https://httpbin.org/get").responseJSON { response in
    print(response.request)  // original URL request
    print(response.response) // HTTP URL response
    print(response.data)     // server data
    print(response.result)   // result of response serialization

    if let JSON = response.result.value {
        print("JSON: \(JSON)")
    }
}

Taken from here: https://github.com/Alamofire/Alamofire#response-ha...

Z
zhenyakim, 2017-05-16
@zhenyakim

ae6fb79bb6e943eaadb1076c62820b40.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question