在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})))
作為 Swift 新手,我認為結構MoveModel
是錯誤的。請幫忙。
另外我想知道是否可以將內部數組的三個元素稱為“我的”、“單詞”、“字母”?
更新:
我已jsonMoves
按照 Joakim 的建議將單引號更改為雙引號(謝謝!),現在錯誤是:
致命錯誤:“嘗試!” 表達式意外引發錯誤:Swift.DecodingError.typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "moves", intValue: nil), _JSONKey(stringValue: "索引 0", intValue: 0), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "預期解碼 Dictionary<String, Any> 但找到了一個數字。",underlyingError: nil))
您可以使用您的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)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句