Siesta JSON Response

414 Views Asked by At

I have set up an API that gives a JSON response as follows:

{
                "key1": "success",
                "key2": {
                    "int_val": 5,
                    "str_val": "email",
                }
}

I've read this, yet still do not understand how I can access key1 properly. I have tried to decode the data in the transformer through [String : Any], which throws an ambiguous type error: "Type of expression is ambiguous".

So how can I read the response with Siesta in the code below?

service.resource("").request(.post, json: userJSON).onSuccess{ entity in
        guard let data = entity.content as? Data else {
            return
        }
        print(data)
    }
3

There are 3 best solutions below

1
Shehata Gamal On BEST ANSWER

You can try Decodable

struct Root:Decodable ( 
  let key1:String
  let key2:InnerItem
}

struct InnerItem:Decodable { 
  let intVal:Int
  let strVal:String
}

do {
    let decoder =  JSONDecoder() 
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let res = decoder.decode(Root.self,from:data)
    print(res.key1) 
}
catch {

    print(error)
 }
0
Peter L On

Parse the Data object as a Dictionary which represents your JSON response.

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

if let key1 = json["key1"] as? String {
    print(key1)
}
0
Paul Cantrell On

The sample project included with Siesta has lots of example of configuring JSON decoding to models. For example, if you have the Root and InnerItem types from @Sh_Khan’s answer:

let decoder = JSONDecoder() 
decoder.keyDecodingStrategy = .convertFromSnakeCase

service.configureTransformer(“/somepath") {
    try jsonDecoder.decode([Root].self, from: $0.content)
}

The important difference from the other answers is the use of service.configureTransformer. Instead of parsing the response every time you use it, configuring a transformer means that it is parsed just once, and everyone sees the parsed result — every onSuccess, everyone who looks at resource.latestData, etc.