在Swift Playground 中,我嘗試決議以下資料:
let jsonMoves:String =
"""
{ "moves":
[
[0, 'CAT (7)', 'ACT'],
[1, 'EXTRA (14)', 'ERXT'],
[0, 'TOP (22)', 'PO'],
[1, 'TOY (9)', 'Y']
]
}
"""
為此,我創建了 2 個結構:
struct MovesResponse: Codable {
let moves: [[MoveModel]]
}
struct MoveModel: Codable {
let mine: Int
let words: String
let letters: String
}
和電話:
let decoder = JSONDecoder()
if let movesData = jsonMoves.data(using: .utf8),
let movesModel = try? decoder.decode(MovesResponse.self, from: movesData),
movesModel.count > 0 // does not compile
{
print("Parsed moves: ", movesModel)
} else {
print("Can not parse moves")
}
不幸的是,上面的代碼給了我編譯錯誤:
“MovesResponse”型別的值沒有成員“count”
當我洗掉該行并更改try?totry!以查看例外時,我收到錯誤訊息:
致命錯誤:“嘗試!” 運算式意外引發錯誤:Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.",underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value在第 3 行,第 12 列周圍。” UserInfo={NSDebugDescription=第 3 行,第 12 列周圍的值無效。,NSJSONSerializationErrorIndex=29})))
Being a Swift newbie, I assume that the struct MoveModel is wrong. Please help.
Also I wonder if it is possible to refer to the three elements of the inner array as "mine", "words", "letters"?
UPDATE:
I have changed single quotes to double quotes in the jsonMoves as suggested by Joakim (thanks!) and the error is now:
Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "moves", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "Expected to decode Dictionary<String, Any> but found a number instead.", underlyingError: nil))
uj5u.com熱心網友回復:
您可以使用您的MoveModel但由于每個內部陣列代表一個實體,MoveModel您需要將第一個結構更改為
struct MovesResponse: Codable {
let moves: [MoveModel]
}
然后你需要一個自定義init(from:),MoveModel它MoveModel使用無鍵容器而不是編碼鍵將每個陣列解碼為一個物件。
init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
mine = try container.decode(Int.self)
words = try container.decode(String.self)
letters = try container.decode(String.self)
}
與其使用try?和列印硬編碼訊息,我建議您捕獲錯誤并列印它
let decoder = JSONDecoder()
do {
let movesModel = try decoder.decode(MovesResponse.self, from: data)
print(movesModel)
} catch {
print(error)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/354491.html
