本文介绍了在Swift 4中解码不带键的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个API,该API返回这个非常糟糕的JSON:

I'm using an API that returns this pretty horrible JSON:

[
  "A string",
  [
    "A string",
    "A string",
    "A string",
    "A string",
    …
  ]
]

我正在尝试使用JSONDecoder解码嵌套数组,但是它没有单个键,而且我真的不知道从哪里开始……你有什么主意吗?

I'm trying to decode the nested array using JSONDecoder, but it doesn't have a single key and I really don't know where to start… Do you have any idea?

非常感谢!

推荐答案

如果结构保持不变,则可以使用此可解码方法.

If the structure stays the same, you can use this Decodable approach.

首先创建一个可解码的模型,如下所示:

First create a decodable Model like this:

struct MyModel: Decodable {
    let firstString: String
    let stringArray: [String]

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        firstString = try container.decode(String.self)
        stringArray = try container.decode([String].self)
    }
}

或者,如果您真的想保留JSON的结构,例如:

Or if you really want to keep the JSON's structure, like this:

struct MyModel: Decodable {
    let array: [Any]

    init(from decoder: Decoder) throws {
        var container = try decoder.unkeyedContainer()
        let firstString = try container.decode(String.self)
        let stringArray = try container.decode([String].self)
        array = [firstString, stringArray]
    }
}

并像这样使用它

let jsonString = """
["A string1", ["A string2", "A string3", "A string4", "A string5"]]
"""
if let jsonData = jsonString.data(using: .utf8) {
    let myModel = try? JSONDecoder().decode(MyModel.self, from: jsonData)
}

这篇关于在Swift 4中解码不带键的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:46