1

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?
}
2
  • Your string it is not a valid JSON. Do you mean "array" :[ ? Commented Nov 19, 2017 at 23:56
  • Note that [Any] doesn't conform to Decodable protocol. Commented Nov 20, 2017 at 0:02

1 Answer 1

6

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.