JSONに小さなエラーがあります(array
の後にコロンがありません)。あなたは、配列の要素は、関連付けられた値を持つ列挙型であることを宣言することができます
let jsonData = """
{
"array": [
33,
{"id": 44, "name": "Jonas"}
]
}
""".data(using: .utf8)!
enum ArrayValue: Decodable {
case int(Int)
case person(Person)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let value = try? container.decode(Int.self) {
self = .int(value)
} else if let value = try? container.decode(Person.self) {
self = .person(value)
} else {
let context = DecodingError.Context(codingPath: container.codingPath, debugDescription: "Unknown type")
throw DecodingError.dataCorrupted(context)
}
}
}
struct Person: Decodable {
var id: Int
var name: String
}
struct ArrayStruct: Decodable {
var array: [ArrayValue]
}
let temp = try JSONDecoder().decode(ArrayStruct.self, from: jsonData)
print(temp.array)
(それはあなたがほとんどの時間を必要とするものが考えられますよう、上記のコードだけDecodable
を示すがEncodable
が同様のアイデアに従っています。)
あなたの文字列には、有効なJSONではありません。あなたは ''配列 ''を意味しますか:['? –
'[Any]'はDecodableプロトコルに準拠していないことに注意してください。 –