I want to decode this JSON with Codable. Without yellow highlighted, this solution worked but if highlighted section comes from server, codable not working. Please help me.
My solution is:
let others : [String: OthersType?]?
enum OthersType: Codable {
case int(Int)
case string(String)
case bool(Bool)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
do {
self = try .int(container.decode(Int.self))
} catch DecodingError.typeMismatch {
do {
self = try .string(container.decode(String.self))
} catch DecodingError.typeMismatch {
do {
self = try .bool(container.decode(Bool.self))
} catch DecodingError.typeMismatch {
throw DecodingError.typeMismatch(OthersType.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Encoded payload not of an expected type"))
}
}
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .int(let int):
try container.encode(int)
case .string(let string):
try container.encode(string)
case .bool(let bool):
try container.encode(bool)
}
}
func getValue(_ ofTheWord: OthersType) -> String {
var result = String(describing: ofTheWord)
if result.contains("string(") {
result = result.replacingOccurrences(of: "string(\"", with: "")
result.removeLast(2)
} else if result.contains("int(") {
result = result.replacingOccurrences(of: "int(", with: "")
result.removeLast(1)
} else if result.contains("bool(") {
result = result.replacingOccurrences(of: "bool(", with: "")
result.removeLast(1)
}
return result
}
}
How to fix this issue with Swift codable?
Please check out this Gist I have created for parsing dynamic key based JSON via Decodable
. https://gist.github.com/aksswami/f30007b71fe78a6d99fff583b38cc480
You can also go through this extensive resource for more Codable basics. https://benscheirman.com/2017/06/swift-json/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.