Search code examples
iosjsonswiftcodabledecodable

how to use this response in Codable method in iOS swift


{
  "response": "success",
  "ads": {
    "imp_url": "https://github.com",
    "ad_type": "Banner Ad",
    "ad_tag": "<script>document.getElementById("demo").innerHTML = "Hello JavaScript!";</script>",
    "click_url": "https://github.com",
    "image_path": ""
  },
  "viewer_token": null
}

Solution

  • Need to set response object to represent all the data in the json:

    struct Response: Codable {
        let response: String?
        let ads: Ads?
        let viewer_token: String?
    }
    
    struct Ads: Codable {
        let imp_url: String?
        let ad_type: String?
        let ad_tag: String?
        let click_url: String?
        let image_path: String?
    }
    

    Then you can get the data in this way:

    func getData() {
    guard let data = try? JSONSerialization.data(withJSONObject: "jsonString", options: []) else {
        // Log error
        return
    }
    var response: Response
    do {
        response = try JSONDecoder().decode(Response.self, from: data)
        // Do something with the response decoded
    } catch let error as NSError {
        // Log error
        return
    }
    

    }

    "jsonString" is your input.