ios - 使用 JSON swift4 中的 key 解码结构

标签 ios swift swift4

使用 Swift 4 的 EncoderDecoder 协议(protocol)和 JSONDecoder 如何使用初始化 Codeable 类型的结构体来自给定 JSON 的 key 。

即鉴于下面的 JSON,我希望仅使用 results 来初始化 Example

{
  "boolean": true,
  "number": 123,
  "results": {
    "a": "b",
    "c": "d",
    "e": "f"
  },
  "string": "Hello World"
}
struct Example: MDB, Codeable{
    var a: String
    var b: String
    var c: String
}
public static func initalize<T: Codable & MDBItem>(json: Data) -> [T]{
        var items = [T]()
        let decoder = JSONDecoder()
        do {
         //How do I initialize `T` using a key from the JSON given
          //ie. decoder.decode([T].self, from: json["results"])
          // Or decoder.decode(["results", [T].self, from: json)
            items = try decoder.decode([T].self, from: json)
                    } catch {
            print("error trying to convert data to JSON")
        }
        return items
    }

最佳答案

一个可能的简单方法是创建一个包装器结构。

所以,你有这个 JSON

let json = """
    {
    "boolean": true,
    "number": 123,
    "results": {
        "a": "b",
        "c": "d",
        "e": "f"
    },
    "string": "Hello World"
    }
    """

由于您只对定义此结构的“结果”部分感兴趣

struct Example: Codable {
    let a: String
    let c: String
    let e: String
}

包装器

现在,为了利用 Codable 协议(protocol)(在 Swift 4 中提供)的强大功能,您可以创建一个像这样的包装器结构

struct Wrapper: Codable {
    let results: Example
}

The only purpose of the Wrapper struct is to define a path from the root of the original JSON to the section you are interested in. This was the Codable protocol will do the rest of the job for you.

解码

现在您可以使用 Wrapper 结构轻松解码 JSON。

if
    let data = json.data(using: .utf8),
    let wrapper = try? JSONDecoder().decode(Wrapper.self, from: data) {

    let results = wrapper.results
    print(results)
}

最后,您可以从包装器中提取 results 属性。

关于ios - 使用 JSON swift4 中的 key 解码结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44731991/

相关文章:

ios - 在ContainerView中打开不同的 View

ios - 将单元格插入 TableView 后调用哪个方法

iphone - MKMapKit 关注用户

ios - 更新标签花费的时间太长(快速)

swift - 如何在 Swift 3 中修复我的自定义 UITextField 对象?

ios - SwiftUI 填充距离不一致

swift - 如何在 swift 中使用 NSLayoutConstraint 根据屏幕尺寸更改设计

ios - Swift4:如何解析 "Fatal error: Can' t form Range with upperBound < lowerBound”?(UI 中的持续时间延迟)

ios - 无法分配类型为 '(String!, Bool, [AnyObject]!, NSError!)->Void to a value of type UIActivityViewControllerCompletionWithItemsHandler?' 的值

ios - Swift + Firebase 安全性不起作用