Swift Codable希望对Dictionary< String,Any>进行解码,但是找到了一个字符串/数据 [英] Swift Codable expected to decode Dictionary<String, Any>but found a string/data instead
问题描述
我一直在使用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个字符串.
I only have to focus on the Object array, and the "image-path" array can contain 0, 1, or 2 strings.
这是我的实现:
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数据后从服务类中调用它:
I call it from my service class after requesting and getting the JSON data this way:
if let data = response.data {
let decoder = JSONDecoder()
let result = try! decoder.decode(Result, from: data)
dump(result.Object)
}
除了image
属性的[String]
以外,其他所有功能都正常工作
Everything is working except the [String]
for the image
property
但是它无法编译,或者出现预期要解码..."错误.
But it can't compile, or I get an "Expected to decode..." error.
我应该如何处理无/无数据情况?
How should I handle the nil/no data scenario?
推荐答案
我对您的MyObject struct
做了小改动,即
I have made a small change in your MyObject struct
, i.e.,
1..将所有properties
标记为optionals
2..已删除init()
(我认为此处没有init()
的任何要求.)
2. Removed init()
(I don't think there is any requirement of init()
here.)
3..在decoder.decode(...)
方法中使用Result.self
代替Result
3. Use Result.self
instead of Result
in decoder.decode(...)
method
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"
}
}
为了测试以上内容,我使用了下面的代码,它工作正常.
To test the above, I have used the below code and it is working fine.
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)
}
这是我得到的结果值:
这篇关于Swift Codable希望对Dictionary< String,Any>进行解码,但是找到了一个字符串/数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!