Last active
June 18, 2019 04:10
-
-
Save xjbeta/41796997bc1d2e168b37a635bf6465ce to your computer and use it in GitHub Desktop.
swift4 codable decode different type in an array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let str = """ | |
{"jsonrpc": "2.0","result": [{"code": 1,"message": "error"},[{"gid": "123"}],{"code": 1,"message": "error2"},[{"gid": "124"}]]} | |
""" | |
let data = str.data(using: .utf8)! | |
struct JSONRPC: Decodable { | |
enum DecodingError : Swift.Error, LocalizedError { | |
case decodeMismatch(type: Any) | |
} | |
enum Result: Decodable { | |
struct ArrayItem: Decodable { | |
let code: Int | |
let message: String | |
} | |
case array(ArrayItem) | |
case dictionary([[String: String]]) | |
init(from decoder: Decoder) throws { | |
let unkeyedContainer = try decoder.singleValueContainer() | |
if let array = try? unkeyedContainer.decode(ArrayItem.self) { | |
self = .array(array) | |
} else if let dic = try? unkeyedContainer.decode([[String: String]].self) { | |
self = .dictionary(dic) | |
} else { | |
throw DecodingError.decodeMismatch(type: decoder) | |
} | |
} | |
} | |
let version: String | |
let results: [Result] | |
private enum CodingKeys: String, CodingKey { | |
case version = "jsonrpc" | |
case results = "result" | |
} | |
} | |
let decoder = JSONDecoder() | |
do { | |
let array = try decoder.decode(JSONRPC.self, from: data) | |
print(array.results) | |
} catch let error { | |
print(error) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment