首页 文章

使用Swift 4 Decodable解析具有混合属性值的JSON

提问于
浏览
0

我正在尝试更新我的应用程序以使用Swift 4 Decodable - 并且正在从具有子值的JSON api中提取数据,该值可能是:

  • 一个子对象

  • 一个字符串

  • 一个Int

这是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?

1 回答

  • 4

    您应该创建一个采用Decodable协议的新Struct,如下所示:

    struct FieldsResponse: Decodable {
        var lastViewed: String
        var timeestimate: Int
    }
    

    然后,您可以将其添加到SupportDeskResponse

    var fields: FieldsResponse
    

相关问题