I am looking to populate my model with the "payload" section from my endpoint. I have created a model of DataResponse which has a record property of Payload. I would like to get only the data from the payload section of the API endpoint. My network call is incorrect and I must be structuring my models wrong, but I am not sure what needs to be fixed. I am not sure if it makes a difference but my endpoint was displaying as an XML and I converted it to JSON below.
struct DataResponse: Decodable {
let record: Payload
}
struct Payload: Decodable {
let SoldToday: Int
}
let url = URL(string: "https:------")!
URLSession.shared.dataTask(with: url) {data, response, error in
guard error == nil,
let data = data else {
print(error)
return
}
let dataResponse = try? JSONDecoder().decode(DataResponse.self, from: data)
if let dataResponse = dataResponse {
print(dataResponse.record.SoldToday)
}
}.resume()
These are the contents of my url endpoint:
{
"action": "API_DoQuery",
"errcode": "0",
"errtext": "No error",
"dbinfo": {
"name": "Daily",
"desc": []
},
"variables": {
"__iol": "&rand=' new Date().getTime())};\">",
"__script": "&rand=' new Date().getTime());void(0);",
"iol": "<img qbu='module' src='/i/clear2x2.gif' onl oad=\"javascript:if(typeof QBU=='undefined'){QBU={};$.getScript(gReqAppDBID '?a=dbpage&pagename=",
"script": "javascript:$.getScript(gReqAppDBID '?a=dbpage&pagename="
},
"chdbids": [],
"record": {
"payload": "{ \"RecordID\": 04-22-2022, \"SoldToday\": 18, \"ContractToday\": 869327, \"KWToday\": 160960 }",
"update_id": "1647544685640"
}
}
CodePudding user response:
you need to fix 2 things to be able to decode your json data:
You need the models that match your json data. Such as:
struct DataResponse: Decodable {
let record: Record
}
struct Record: Decodable {
let payload: Payload
}
struct Payload: Decodable {
let SoldToday: Int
}
And you need to make sure your data is valid json. Currently variables
is not valid, similarly for payload
in record
,
(it is enclosed in quotes). Once these are fixed, I was able to decode the data successfully in my tests.
Note that if your endpoint is giving you XML, then it is probably better to convert XML to your models directly, without having to convert to json. There are a number of XML parser libraries on github.