【问题标题】:How do I decode a JSON file containing arrays Swift 4?如何解码包含数组 Swift 4 的 JSON 文件?
【发布时间】:2018-08-06 18:43:12
【问题描述】:

我有一个 JSON 文件,我正在尝试解码,但收到一条错误消息:

typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "期望解码 Dictionary 但找到了一个数组。", 底层错误:无))

我的代码如下:

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"]
]

我知道解码器正在寻找字典,但我如何让它解码数组呢?

【问题讨论】:

    标签: json swift


    【解决方案1】:

    我认为你需要

    let jsonSentence = try jsonDecoder.decode([[String]].self, from: jsonData)
    

    【讨论】:

    • +1。 Hardy143,您不能使用 struct Phrase,因为 JSON 没有 sentences 键。您的 JSON 是一个数组数组。
    • @subdan 这里没有键
    【解决方案2】:

    您的 JSON 数据与您要解析的结构不匹配。 JSON 是一个 字符串数组数组,而您尝试解析一个 Phrase 对象数组。

    解决方案 1:要保持 JSON 结构原样,您需要解析一个数组数组,或者通过使用类型别名来保持自定义模型类型:

    typealias Phrase = [String]
    

    解决方案 2:要保持您定义的 struct 原样,您必须将 JSON 格式更改为此;

    [
      { "sentences": ["bin blue", "with A 2 soon"] },
      { "sentences": ["set blue", "in A 9 soon"] },
      ...
    ]
    

    这两种解决方案都适用于您的 getFromJSON 实现。

    【讨论】:

    • 非常感谢。我选择了解决方案 1,效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多