简体   繁体   中英

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
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM