我观看了 WWDC session 102 并尝试使用 JSONDecoder 进行建模,但我有一个问题,这是我的结构
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
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
该属性images无法解码,因为我删除了它可以成功,但我不知道如何修复,请告诉我,谢谢
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)"
}
Run Code Online (Sandbox Code Playgroud)
--------- 最后更新 2017.6.17 ----------
let images : Array<String> -> let images : Array<String>?
Run Code Online (Sandbox Code Playgroud)
图片为空时需要可选属性,谢谢您的帮助
该属性used应该是,Bool但结构被正确解码
do {
let decoded = try JSONDecoder().decode(DataListModel.self, from: data)
print(decoded)
} catch {
print(error)
}
Run Code Online (Sandbox Code Playgroud)
假设data是 JSONData对象。
| 归档时间: |
|
| 查看次数: |
5693 次 |
| 最近记录: |