我有一个JSON文件,我正在尝试解码,但得到了一个错误消息:
typeMismatch(Swift.Dictionary,Swift.DecodingError.Context(codingPath:_JSONKey(stringValue:“索引0",intValue: 0),debugDescription:”期望解码字典,但找到了一个数组。“,underlyingError: nil)
我的代码如下:
struct Phrase: Decodable {
let sentences: [String]
}
func getFromJSON() {
do {
let jsonURL = Bundle.main.url(forResource: "script", withExtension: "json")
let jsonDecoder = JSONDecoder()
let jsonData = try Data(contentsOf: jsonURL!)
let jsonSentence = try jsonDecoder.decode([Phrase].self, from: jsonData)
debugPrint(jsonSentence)
} catch {
print(error)
}
}
我一直在研究许多其他堆栈溢出问题,我注意到这些JSON文件的格式与我的不同。它们被格式化为字典,而我的格式是这样的-
[
["bin blue", "with A 2 soon"],
["set blue", "in A 9 soon"],
["lay blue", "at A 3 please"],
["3 5 zero zero 5 8"],
["place blue", "by A 6 now"],
["lay green", "at B ZERO now"],
["8 9 1 5 4 zero"]
]
我知道解码器正在寻找字典,但是我如何让它解码数组呢?
发布于 2018-08-07 03:04:11
我觉得你需要
let jsonSentence = try jsonDecoder.decode([[String]].self, from: jsonData)
发布于 2018-08-07 03:19:52
您的JSON数据与要解析的结构不匹配。JSON是一个字符串数组数组,而您试图解析一个Phrase
对象数组。
JSON 1JSON:为了保持结构不变,您需要解析数组数组,或者通过使用类型别名来保留自定义模型类型:
typealias Phrase = [String]
JSON 2JSON:为了保持您定义的的原样,您必须将struct
格式更改为:
[
{ "sentences": ["bin blue", "with A 2 soon"] },
{ "sentences": ["set blue", "in A 9 soon"] },
...
]
这两种解决方案都适用于您的getFromJSON
实现。
https://stackoverflow.com/questions/51713830
复制相似问题