Swift-如何将平面json解码为嵌套结构?

基兰

假设我有以下JSON,我想将其解码为特定的结构。我该怎么做呢

JSON:

{
 "fullName": "Federico Zanetello",
 "id": 123456,
 "twitter": "http://twitter.com/zntfdr",
 "results": ["mate","bate"]
}

解码结构

struct Response {
    let data: UserData,
    let results: [String]
}

UserData结构

Struct UserData {
   let fullName: String,
   let id: Int,
   let twitter: String
}

我进行了研究,找不到有效的解决方案。这是我到目前为止编写的代码

struct UserData: Decodable {
    let fullName: String
    let id: Int
    let twitter: String
    
    enum CodingKeys: String, CodingKey {
        case fullName
        case id
        case twitter
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        self.fullName = try container.decode(String.self, forKey: .fullName)
        self.id = try container.decode(Int.self, forKey: .id)
        self.twitter = try container.decode(String.self, forKey: .twitter)
    }
}

struct Respone: Decodable{
    let data: UserData
    let results: [String]
}

let json = """
{
 "fullName": "Federico Zanetello",
 "id": 123456,
 "twitter": "http://twitter.com/zntfdr",
 "results": ["mate","bate"]
}
""".data(using: .utf8)! // our data in native (JSON) format
let myStruct = try JSONDecoder().decode(MetaData.self, from: json) // Decoding our data
print(myStruct)

我收到KeynotFound错误,因为dataJSON中不存在密钥。我该如何解决?

清扫器

您可以执行以下操作:

struct UserData: Decodable {
    let fullName: String
    let id: Int
    let twitter: String
}

struct Response: Decodable{
    let data: UserData
    let results: [String]
    
    enum CodingKeys : CodingKey {
        case results
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        results = try container.decode([String].self, forKey: .results)
        data = try decoder.singleValueContainer().decode(UserData.self)
    }
}

诀窍是在中使用自定义解码Response,然后像平常一样解码后results,得到一个singleValueContainer此容器将包含JSON中的所有键,因此您可以使用此容器解码UserData

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章