相关疑难解决方法(0)

在Swift中动态解码任意json字段

TL; DR

有没有一种方法可以使用JSONDecoder并编写一个函数,它只是从给定的json读出指定的可解码类型的字段值?


成像我有以下json:

{
   "product":{
      "name":"PR1",
      "price":20
   },
   "employee":{
      "lastName":"Smith",
      "department":"IT",
      "manager":"Anderson"
   }
}
Run Code Online (Sandbox Code Playgroud)

我有2个Decodable结构:

struct Product: Decodable {
    var name: String
    var price: Int
}

struct Employee: Decodable {
    var lastName: String
    var department: String
    var manager: String
}
Run Code Online (Sandbox Code Playgroud)

我想写一个函数

func getValue<T:Decodable>(from json: Data, field: String) -> T { ... }
Run Code Online (Sandbox Code Playgroud)

所以我可以这样称呼它:

let product: Product = getValue(from: myJson, field: "product")
let employee: Employee = getValue(from: myJson, field: "employee")
Run Code Online (Sandbox Code Playgroud)

这是可能的,JSONDecoder或者我应该弄乱JSONSerialization,首先读出给定json的"子树",然后将其传递给解码器?在swift中似乎不允许在泛型函数中定义结构.

json nsjsonserialization swift jsondecoder

5
推荐指数
1
解决办法
478
查看次数

Swift Codable:使用父级的键作为值

我有一个 JSON,其 ID 在根级别:

{
    "12345": {
        "name": "Pim"
    },
    "54321": {
        "name": "Dorien"
    }
}
Run Code Online (Sandbox Code Playgroud)

我的目标是使用 Codable 创建一个同时具有 name 和 ID 属性的 User 对象数组。

struct User: Codable {
    let id: String
    let name: String
}
Run Code Online (Sandbox Code Playgroud)

我知道如何使用带有单个根级别密钥的Codable ,并且知道如何使用未知密钥。但我在这里尝试做的是两者的结合,我不知道下一步该做什么。

这是我到目前为止得到的:(您可以将其粘贴到 Playground 中)

import UIKit

var json = """
{
    "12345": {
        "name": "Pim"
    },
    "54321": {
        "name": "Dorien"
    }
}
"""

let data = Data(json.utf8)

struct User: Codable {
    let name: String
}

let decoder = JSONDecoder() …
Run Code Online (Sandbox Code Playgroud)

swift codable decodable jsondecoder

2
推荐指数
1
解决办法
1728
查看次数

Swift 4 可解码多个容器

我试图了解如何将这个多容器 JSON 解析为一个对象。我已经尝试过这种方法(Mark answer),但他解释了如何使用一级容器解决它。出于某种原因,我无法模仿多个容器的行为。

 {
     "graphql": {
        "shortcode_media": {
          "id": "1657677004214306744",
          "shortcode": "BcBQHPchwe4"
        }
     }
  }
Run Code Online (Sandbox Code Playgroud)
class Post: Decodable {


    enum CodingKeys: String, CodingKey {
        case graphql // The top level "user" key
        case shortcode_media
    }

    enum PostKeys: String, CodingKey {
        case id
    }

    required init(from decoder: Decoder) throws {

        let values = try decoder.container(keyedBy: CodingKeys.self)

        let post = try values.nestedContainer(keyedBy: PostKeys.self, forKey: .shortcode_media)

        self.id = try post.decode(String.self, forKey: .id)

    }

    var id: String

}
Run Code Online (Sandbox Code Playgroud)

我越来越:

Swift.DecodingError.Context(codingPath: [], …
Run Code Online (Sandbox Code Playgroud)

containers json swift4 codable decodable

1
推荐指数
1
解决办法
2175
查看次数