這個問題在這里已經有了答案: 你如何設計一個可編碼的 JSON 欄位,它可以是一個空字串或一個 int [關閉] (1 個回答) 22 小時前關閉。
我正在嘗試從 API 呼叫中解碼 JSON 資料,并有一些可解碼的類來解碼 JSON,但我遇到了一個問題。在 JSON 中,有一個具有相同名稱的專案(假設為“值”),但字串或整數取決于它的“型別”。
有人可以幫我在這種情況下如何構建我的可解碼類嗎?(我的示例可解碼類如下)
class ExampleClassToDecode: Decodable {
let type: String
let value: String? // this item can be either String or Int in the callback JSON data
}
示例 JSON
0:{
"type":"type1"
"value":"73%"
}
1:{
"type":"type2"
"value":2
}
2:{
"type":"type3"
"value":NULL
}
uj5u.com熱心網友回復:
您可以使用具有關聯值的列舉。
可編碼的一致性:
struct Example: Codable {
let type: String
let value: Value?
}
enum Value: Codable {
case string(String)
case int(Int)
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let string = try? container.decode(String.self) {
self = .string(string)
return
}
if let int = try? container.decode(Int.self) {
self = .int(int)
return
}
throw CodableError.failedToDecodeValue
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .string(let string): try container.encode(string)
case .int(let int): try container.encode(int)
}
}
}
enum CodableError: Error {
case failedToDecodeValue
}
用法:
let json1 = """
{
"type": "type1",
"value": "73%"
}
"""
let json2 = """
{
"type": "type2",
"value": 2
}
"""
let json3 = """
{
"type": "type3",
"value": null
}
"""
do {
let data = Data(json1.utf8) // <- Swap this for other JSONs
let result = try JSONDecoder().decode(Example.self, from: data)
print(result)
switch result.value {
case .string(let string): print("percentage: \(string)")
case .int(let int): print("counter: \(int)")
case nil: print("no value")
}
} catch {
print(error)
}
uj5u.com熱心網友回復:
我會將它保留String在您的可解碼模型類中,而在您的視圖控制器中,我將使用type來了解如何將value. 如果是,type1那么我將知道該值是 a String。如果是,type2那么我知道那是一個,Int所以我將字串轉換為 Int。
編輯:George 示例是一個更好的主意,因為它是在 Model 類中進行轉換的,因此您以后無需在 ViewController 中擔心。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/366622.html
