[英]How to parse key value json with Codable?
我想用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解決此問題?
請查看我為通過Decodable
解析基於動態密鑰的JSON而創建的Decodable
。 https://gist.github.com/aksswami/f30007b71fe78a6d99fff583b38cc480
您也可以瀏覽此廣泛的資源,以獲得更多的Codable基礎知識。 https://benscheirman.com/2017/06/swift-json/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.