我想用Codable解码此JSON。 如果未突出显示黄色,则该解决方案有效,但如果突出显示的部分来自服务器,则可编码不起作用。 请帮助我。
我的解决方法是:
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
}
}
如何使用Swift codable解决此问题?
答案 0 :(得分:0)
请查看我为通过Decodable
解析基于动态密钥的JSON而创建的要点。
https://gist.github.com/aksswami/f30007b71fe78a6d99fff583b38cc480
您也可以浏览此广泛的资源以获取更多有关Codable的基础知识。 https://benscheirman.com/2017/06/swift-json/