2

i know this is very basic question that i am gonna ask but i need to ask how can i access data which is dictionary that is getting from server.

here is my response

JSON: {
message = "The email must be a valid email address.";}

enter image description here

now i want to do "po" in console log so what to write after in po statement

Thanks

Bhaumik Joshi
  • 245
  • 1
  • 7
  • 17

1 Answers1

1

All you need type

po yourResponseAsDictionary["message"]

UPDATED

Sorry I was thinking you already converted it.

If you are not using anything like SwiftyJSON or ObjectMapper to parse your json data then you can do just the following. But I would recommend to use some lib to convert response directly to your model

let yourResponseFromNetwork = "{ \"country_code\" : \"+9\", \"user_id\" : 123456}"
if let data = yourResponseFromNetwork.data(using: String.Encoding.utf8) {
    do {
        if let dic = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any] {
            let countryCode = dic["country_code"]
            let userId = dic["user_id"]
        }
    } catch {
        print("Error occurred")
    }
}
mihatel
  • 846
  • 14
  • 34
  • can you tell me same for given response – Bhaumik Joshi Dec 14 '17 at 09:39
  • SUCCESS: { userResult = ( { "country_code" = "+9"; "created_at" = "2017-12-08 10:19:05"; dob = ""; email = “sdf@sdf.com”; gender = Male; "is_social" = 0; isuserverified = 1; password = “sfds”; "phone_no" = 997234268; "profile_pic" = "12342”; "updated_at" = "2017-12-08 10:19:40"; "user_id" = 16; username = sdf; } ); } – Bhaumik Joshi Dec 14 '17 at 09:39
  • how can i get value of keys of "user_id" or "country_code" etc – Bhaumik Joshi Dec 14 '17 at 09:40
  • No bro... i want to know how to access those dat a in swift which is coming from server side.... can u guide me how can i do it. – Bhaumik Joshi Dec 14 '17 at 16:33
  • @BhaumikJoshi Not sure get the point, you mean how to send GET request and receive response ? – mihatel Dec 14 '17 at 19:27
  • no no..i already done calling of POST request now i get response of it okay and also i show u my response in above comment...till now everything is perfect but now how can i access each value from that response got me now? – Bhaumik Joshi Dec 15 '17 at 05:04
  • instead of for example printing country code "print(dic["country_code"])" just get it let countryCode = dic["country_code"], or for user id, let userId = dic["user_id"] – mihatel Dec 15 '17 at 06:13
  • I've changed answer, is it what you need? – mihatel Dec 15 '17 at 06:16
  • you are just near to my point but not exactly see first of teel me how can i add server response to local dictionary ? so once i add response in local dictionary ll goto the next step got me ? – Bhaumik Joshi Dec 15 '17 at 06:18
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/161264/discussion-between-mihatel-and-bhaumik-joshi). – mihatel Dec 15 '17 at 06:21