首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >嵌套对象swift4可编码解码

嵌套对象swift4可编码解码
EN

Stack Overflow用户
提问于 2017-11-25 18:00:40
回答 1查看 696关注 0票数 1

API发送给我这个json:

代码语言:javascript
复制
{
"name": "John Doe",
"details": [{
    "name": "exampleString"
}, {
    "name": [1, 2, 3]
}]

}

这里的问题是,details数组有两个不同值类型的字典。如何使用swift4的可解码协议在模型中解码这个json?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-25 18:28:25

我不建议您使用异构类型来构造您的JSOn;在这种情况下,details.name可以是字符串,也可以是Int数组。虽然您可以这样做,但它很混乱,因为默认情况下它是一种静态类型的语言。如果您不能在这里将JSON更改为更干净的东西,那么一个游乐场展示了您如何选择使用Any进行动态行为。

代码语言:javascript
复制
//: Playground - noun: a place where people can play
import PlaygroundSupport
import UIKit

let json = """
{
"name": "John Doe",
"details": [{
"name": "exampleString"
}, {
"name": [1, 2, 3]
}]
}
"""


struct Detail {
    var name: Any?
    var nameString: String? {
        return name as? String
    }
    var nameIntArray: [Int]? {
        return name as? [Int]
    }
    enum CodingKeys: CodingKey {
        case name
    }
}

extension Detail: Encodable {
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        if let string = name as? String {
            try container.encode(string, forKey: .name)
        }
        if let array = name as? [Int] {
            try container.encode(array, forKey: .name)
        }
    }
}


extension Detail: Decodable {
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        if let string = try? values.decode(String.self, forKey: .name) {
            name = string
        } else if let array = try? values.decode(Array<Int>.self, forKey: .name) {
            name = array
        }
    }
}

struct Record: Codable {
    var name: String
    var details: [Detail]
}

let jsonDecoder = JSONDecoder()
let record = try! jsonDecoder.decode(Record.self, from: json.data(using: .utf8)!)
print("\(record.details.first!.name!) is of type: \(type(of:record.details.first!.name!))")
print("\(record.details.last!.name!) is of type: \(type(of:record.details.last!.name!))")

产出如下:

代码语言:javascript
复制
exampleString is of type: String
[1, 2, 3] is of type: Array<Int>
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47489010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档