我正在尝试更新我的应用程序以使用Swift 4 Decodable - 并且正在从具有子值的JSON api中提取数据:
以下是Json Api回复:
var jsonoutput =
"""
{
"id": "124549",
"key": "TEST-32",
"fields": {
"lastViewed": "2018-02-17T21:40:38.864+0000",
"timeestimate": 26640
}
}
""".data(using: .utf8)
我试图使用以下内容解析它:如果我只引用两个字符串的id和key属性,它就可以工作。
struct SupportDeskResponse: Decodable{
var id: String
var key: String
//var fields: [String: Any] //this is commented out as this approach doesn't work - just generated a decodable protocol error.
}
var myStruct: Any!
do {
myStruct = try JSONDecoder().decode(SupportDeskResponse.self, from: jsonoutput!)
} catch (let error) {
print(error)
}
print(myStruct)
如何将字段对象解码为我的Struct?
答案 0 :(得分:4)
您应该创建一个采用Decodable协议的新Struct,如下所示:
undefined
然后您可以将其添加到SupportDeskResponse
struct FieldsResponse: Decodable {
var lastViewed: String
var timeestimate: Int
}