API发送给我这个json:
{
"name": "John Doe",
"details": [{
"name": "exampleString"
}, {
"name": [1, 2, 3]
}]
}
这里的问题是details数组有两个不同值类型的字典。 如何使用swift4的可解码协议解码模型中的这个json?
答案 0 :(得分:1)
我不建议您使用异类型构建JSOn;在这个案例中,details.name可以是字符串或Int数组。虽然你可以做到这一点是Swift,它默认是一种静态的静态类型语言。如果您无法将JSON更改为更干净的内容,则可以通过Any
向您展示如何选择动态行为。
//: 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!))")
输出是:
exampleString is of type: String
[1, 2, 3] is of type: Array<Int>