我一直在使用Codable
协议
这是我的JSON
文件:
{
"Adress":[
],
"Object":[
{
"next-date":"2017-10-30T11:00:00Z",
"text-sample":"Some text",
"image-path":[
"photo1.png",
"photo2.png"
],
"email":"john.doe@test.com",
"id":"27"
},
{
"next-date":"2017-10-30T09:00:00Z",
"text-sample":"Test Test",
"image-path":[
"image1.png"
],
"email":"name.lastename@doe.com",
"id":"28"
}
]
}
我只需要专注于Object数组,以及" image-path"数组可以包含0,1或2个字符串。
所以这是我的实施:
struct Result: Codable {
let Object: [MyObject]
}
struct MyObject: Codable {
let date: String
let text: String
let image: [String]
let email: String
let id: String
enum CodingKeys: String, CodingKey {
case date = "next-date"
case text = "text-sample"
case image = "image-path"
case email = "email"
case id = "id"
}
init() {
self.date = ""
self.text = ""
self.image = []
self.email = ""
self.id = ""
}
}
在以这种方式请求和获取JSON数据后,我从我的服务类中调用它:
if let data = response.data {
let decoder = JSONDecoder()
let result = try! decoder.decode(Result, from: data)
dump(result.Object)
}
除[String]
属性
image
外,其他所有工作都有效
但是它无法编译,或者我得到了一个"期望解码......"错误。
我应该如何处理nil / no数据场景?
答案 0 :(得分:5)
我对你的MyObject struct
进行了一些小改动,即
1。将所有properties
标记为optionals
2。已移除init()
(我认为此处不需要init()
。)
3。在Result.self
方法中使用Result
代替decoder.decode(...)
struct MyObject: Codable
{
let date: String?
let text: String?
let image: [String]?
let email: String?
let id: String?
enum CodingKeys: String, CodingKey
{
case date = "next-date"
case text = "text-sample"
case image = "image-path"
case email = "email"
case id = "id"
}
}
为了测试上述内容,我使用了以下代码,它运行正常。
let jsonString = """
{"Adress": [],
"Object": [{"next-date": "2017-10-30T11:00:00Z",
"text-sample": "Some text",
"image-path": ["photo1.png", "photo2.png"],
"email": "john.doe@test.com",
"id": "27"},
{"next-date": "2017-10-30T09:00:00Z",
"text-sample": "Test Test",
"image-path": ["image1.png"],
"email": "name.lastename@doe.com",
"id": "28"}
]
}
"""
if let data = jsonString.data(using: .utf8)
{
let decoder = JSONDecoder()
let result = try? decoder.decode(Result.self, from: data) //Use Result.self here
print(result)
}
这是我得到的结果值: