I watch WWDC session 102 and I try to use JSONDecoder to model,but I have a question,this is my struct
public struct DataListResult:Codable{
let _id : String
let createdAt : String
let desc : String
let images : Array<String>
let publishedAt : String
let source : String
let type : String
let url : String
let used : Int
let who : String
}
public struct DataListModel:Codable{
let results : [DataListResult]
let error: Bool
}
JSON:
{
"results" : [
{
"_id" : "59266a79421aa92c73b6475c",
"images" : [
"http:\/\/img.gank.io\/875a9508-3a1e-4d4b-8b91-c111ea62871a"
],
"source" : "chrome",
"who" : "S",
"publishedAt" : "2017-05-25T13:32:48.92Z",
"used" : true,
"createdAt" : "2017-05-25T13:24:09.35Z",
"type" : "iOS",
"desc" : "iOS ",
"url" : "https:\/\/github.com\/adamzjk\/iOS-ObjectDetection"
},
{
"_id" : "592502d6421aa92c769a8bac",
"images" : [
"http:\/\/img.gank.io\/44e8aa0a-b66f-4a5b-9cb0-74c3ae9fc156"
],
"source" : "chrome",
"who" : "S",
"publishedAt" : "2017-05-24T12:09:25.526Z",
"used" : true,
"createdAt" : "2017-05-24T11:49:42.14Z",
"type" : "iOS",
"desc" : "Whatʼs new in Swift 4",
"url" : "https:\/\/github.com\/ole\/whats-new-in-swift-4"
},
{
"_id" : "5923a438421aa92c73b64743",
"images" : [
"http:\/\/img.gank.io\/25762b53-b2ba-4c1c-9666-1683cd72bb82"
],
"source" : "chrome",
"who" : "who",
"publishedAt" : "2017-05-23T11:14:05.141Z",
"used" : true,
"createdAt" : "2017-05-23T10:53:44.853Z",
"type" : "iOS",
"desc" : "music",
"url" : "https:\/\/github.com\/HarshilShah\/DeckTransition"
}
],
"error" : false
}
The property images
can't decoded,because I remove this it can be success,but I don't know how to fix,please tell me, thank you
do
{
let model = try JSONDecoder().decode(DataListModel.self, from: response.data!)
}catch let error as NSError {
print("\(error)") //Error Domain=Swift.DecodingError Code=2 "(null)"
}
--------- last update 2017.6.17 ----------
let images : Array<String> -> let images : Array<String>?
images need opotional property when it empty,thank you for your help
The property used
is supposed to be Bool
but the structure is decoded correctly with
do {
let decoded = try JSONDecoder().decode(DataListModel.self, from: data)
print(decoded)
} catch {
print(error)
}
assuming data
is the JSON Data
object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With