我定義了這個結構。
import Foundation
import SwiftUI
struct Hoge: Hashable, Codable {
var id: Int
var type: Type
}
enum Type: Codable {
case one
case two
}
我創建了 json。
[
{
"id": 1,
"type": "one",
},
...
]
這是解碼和加載 json 檔案。
import Foundation
var hogeList: [Hoge] = load("hoge.json")
func load<T: Decodable>(_ filename: String) -> T {
let data: Data
guard let file = Bundle.main.url(forResource: filename, withExtension: nil) else {
fatalError("Couldnt find \(filename) in main bundle.")
}
do {
data = try Data(contentsOf: file)
} catch {
fatalError("Couldnt load \(filename) from main bundle:\n\(error)")
}
do {
let decoder = JSONDecoder()
return try decoder.decode(T.self, from: data)
} catch {
fatalError("Couldnt parse \(filename) as \(T.self):\n\(error)")
}
}
破解日志顯示此日志。
致命錯誤:無法將 hoge.json 決議為陣列:typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue) : "type", intValue: nil)], debugDescription: "期望解碼 Dictionary<String, Any> 但找到了一個字串/資料。",底層錯誤: nil))
uj5u.com熱心網友回復:
您的代碼中有兩個問題:
a)您的 JSON 中有一個額外的逗號,使其無效。去掉“一”后面的逗號
[
{
"id": 1,
"type": "one"
}
]
b)您需要將您的列舉型別宣告為字串:
enum Type: String, Codable {
case one, two
}
注意:我還將列舉從 重命名Type為Kind。您還需要更改 json 或為您的結構提供自定義 CodingKeys
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/426820.html
上一篇:洗掉JSON陣列中的值
