在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”类型的值没有成员“计数”
当我删除该行并将其更改try?
为try!
查看异常时,我会收到错误消息:
致命错误:“试试!” 表达式意外引发错误: 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: " Index 0", intValue: 0), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "期望解码 Dictionary<String, Any> 但找到了一个数字。",底层错误: nil))