user3384741
user3384741

Reputation: 1340

Swift 4 codable array with both object and int

Let's say I have this JSON:

{
   "array": [
       33,
       {"id": 44, "name": "Jonas"}
   ]
}

How do I write a swift 4 Codable struct to deserialize this JSON?

struct ArrayStruct : Codable {
    // What do I put here?
}

Upvotes: 1

Views: 574

Answers (1)

Code Different
Code Different

Reputation: 93151

Your JSON contains a small error (missing a colon after array). You can declare your array's element being an enum with associated value:

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)

(The above code only show Decodable as that's likely what you need most of the time. But Encodable follows similar ideas)

Upvotes: 6

Related Questions