Just icon indicating copy to clipboard operation
Just copied to clipboard

Utilizing r.json response?

Open szumlins opened this issue 5 years ago • 2 comments

Apologies if this is a dumb question, but I am relatively new to Swift. I've implemented this in a little sandbox and can properly make a post call to my end point and get a proper response.

I'm very familiar with Python requests, so I was hoping that I would be able to address the r.json object similarly in Swift, but no matter what I do, I can't seem to figure out how to actually get key out of the r.json object. I can print it and see it is valid, but when I try to something simple (in my mind) like print(r.json["my_key"]) I can't.

This is probably more of a lack of understanding of the object type that r.json returns in swift and how to get info out of it, but I figured I'd ask because I love the idea of just using my familiarity with Python requests to start my voyage into Swift programming.

szumlins avatar Jan 21 '21 03:01 szumlins

I believe you have to cast it first.

let result = r.json! as! [String: String]

print(result["my_key"])

I am new as well, so I'm not sure if there is a better approach, but Python and Swift are very different languages. Python is interpreted language and Swift is a compiled language. So you have to cast it first. If you want my suggestion, do not use this kind of approach in Swift unless it's only for debug purposes. Create a Model class first, after getting the response, add the response to the Model class that you created.

This is an example when using Reddit api to login:

LoginModel.swift

struct LoginModel: Decodable {
    let access_token: String
    let expires_in: Int
    let scope: String
    let token_type: String
}

And after getting the response from Just you just have to write this code:

if r.ok {
    let resp = try? JSONDecoder().decode(LoginModel.self, from: r.content!)
}

Then you can get the values:

print(resp.access_token)

aldo-o avatar Jun 11 '21 15:06 aldo-o

Thank you for this! I'll give it a try.

szumlins avatar Jun 12 '21 14:06 szumlins