Swift:Codable - 提取单个编码密钥

时间:2018-05-17 10:38:41

标签: ios json swift codable decodable

我有以下代码来提取编码密钥中包含的JSON:

let value = try! decoder.decode([String:Applmusic].self, from: $0["applmusic"])

这成功处理了以下JSON:

{
  "applmusic":{
    "code":"AAPL",
    "quality":"good",
    "line":"She told me don't worry",
}

但是,无法从以下代码中提取编码密钥为applmusic的JSON:

{
  "applmusic":{
    "code":"AAPL",
    "quality":"good",
    "line":"She told me don't worry",
  },
  "spotify":{
    "differentcode":"SPOT",
    "music_quality":"good",
    "spotify_specific_code":"absent in apple"
  },
  "amazon":{
    "amzncode":"SPOT",
    "music_quality":"good",
    "stanley":"absent in apple"
  }
}

applmusicspotifyamazon的数据模型不同。但是,我只需要提取applmusic并省略其他编码密钥。

我的Swift数据模型如下:

public struct Applmusic: Codable {
    public let code: String
    public let quality: String
    public let line: String
}

API以完整的JSON响应,我不能要求它只给我所需的字段。

如何只解码json的特定部分?似乎Decodable要求我先对整个json进行反序列化,所以我必须知道它的完整数据模型。

显然,其中一个解决方案是创建一个单独的Response模型,只是为了包含applmusic参数,但它看起来像是一个黑客:

public struct Response: Codable {
    public struct Applmusic: Codable {
        public let code: String
        public let quality: String
        public let line: String
    }
    // The only parameter is `applmusic`, ignoring the other parts - works fine
    public let applmusic: Applmusic
}

你能提出一个更好的方法来处理这样的JSON结构吗?

更深入了解

我在通用扩展中使用以下技术,为我自动解码API响应。因此,我倾向于概括一种处理此类案例的方法,而无需创建Root结构。如果我需要的密钥在JSON结构中是3层深度怎么办?

以下是为我解码的扩展程序:

extension Endpoint where Response: Swift.Decodable {
  convenience init(method: Method = .get,
                   path: Path,
                   codingKey: String? = nil,
                   parameters: Parameters? = nil) {
    self.init(method: method, path: path, parameters: parameters, codingKey: codingKey) {
      if let key = codingKey {
        guard let value = try decoder.decode([String:Response].self, from: $0)[key] else {
          throw RestClientError.valueNotFound(codingKey: key)
        }
        return value
      }

      return try decoder.decode(Response.self, from: $0)
    }
  }
}

API的定义如下:

extension API {
  static func getMusic() -> Endpoint<[Applmusic]> {
    return Endpoint(method: .get,
                    path: "/api/music",
                    codingKey: "applmusic")
  }
}

3 个答案:

答案 0 :(得分:4)

更新:我将JSONDecoder扩展为此答案,您可以在此处查看:https://github.com/aunnnn/NestedDecodable,它允许您使用关键路径解码任何深度的嵌套模型

你可以像这样使用它:

let post = try decoder.decode(Post.self, from: data, keyPath: "nested.post")

您可以创建一个Decodable包装器(例如,ModelResponse),并将所有逻辑用于提取嵌套模型,其中包含一个键:

struct DecodingHelper {

    /// Dynamic key
    private struct Key: CodingKey {
        let stringValue: String
        init?(stringValue: String) {
            self.stringValue = stringValue
            self.intValue = nil
        }

        let intValue: Int?
        init?(intValue: Int) {
            return nil
        }
    }

    /// Dummy model that handles model extracting logic from a key
    private struct ModelResponse<NestedModel: Decodable>: Decodable {
        let nested: NestedModel

        public init(from decoder: Decoder) throws {
            let key = Key(stringValue: decoder.userInfo[CodingUserInfoKey(rawValue: "my_model_key")!]! as! String)!
            let values = try decoder.container(keyedBy: Key.self)
            nested = try values.decode(NestedModel.self, forKey: key)
        }
    }

    static func decode<T: Decodable>(modelType: T.Type, fromKey key: String) throws -> T {
        // mock data, replace with network response
        let path = Bundle.main.path(forResource: "test", ofType: "json")!
        let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe)

        let decoder = JSONDecoder()

        // ***Pass in our key through `userInfo`
        decoder.userInfo[CodingUserInfoKey(rawValue: "my_model_key")!] = key
        let model = try decoder.decode(ModelResponse<T>.self, from: data).nested
        return model
    }
}

您可以通过userInfo JSONDecoder "my_model_key"的{​​{1}}传递所需的密钥。然后将其转换为Key内的动态ModelResponse以实际提取模型。

然后你可以像这样使用它:

let appl = try DecodingHelper.decode(modelType: Applmusic.self, fromKey: "applmusic")
let amazon = try DecodingHelper.decode(modelType: Amazon.self, fromKey: "amazon")
let spotify = try DecodingHelper.decode(modelType: Spotify.self, fromKey: "spotify")
print(appl, amazon, spotify)

完整代码: https://gist.github.com/aunnnn/2d6bb20b9dfab41189a2411247d04904

奖励:深层嵌套密钥

在玩了更多之后,我发现你可以使用这个修改过的ModelResponse轻松解码任意深度的键:

private struct ModelResponse<NestedModel: Decodable>: Decodable {
    let nested: NestedModel

    public init(from decoder: Decoder) throws {
        // Split nested paths with '.'
        var keyPaths = (decoder.userInfo[CodingUserInfoKey(rawValue: "my_model_key")!]! as! String).split(separator: ".")

        // Get last key to extract in the end
        let lastKey = String(keyPaths.popLast()!)

        // Loop getting container until reach final one
        var targetContainer = try decoder.container(keyedBy: Key.self)
        for k in keyPaths {
            let key = Key(stringValue: String(k))!
            targetContainer = try targetContainer.nestedContainer(keyedBy: Key.self, forKey: key)
        }
        nested = try targetContainer.decode(NestedModel.self, forKey: Key(stringValue: lastKey)!)
    }

然后你可以像这样使用它:

let deeplyNestedModel = try DecodingHelper.decode(modelType: Amazon.self, fromKey: "nest1.nest2.nest3")

来自这个json:

{
    "apple": { ... },
    "amazon": {
        "amzncode": "SPOT",
        "music_quality": "good",
        "stanley": "absent in apple"
    },
    "nest1": {
        "nest2": {
            "amzncode": "Nest works",
            "music_quality": "Great",
            "stanley": "Oh yes",

            "nest3": {
                "amzncode": "Nest works, again!!!",
                "music_quality": "Great",
                "stanley": "Oh yes"
            }
        }
    }
}

完整代码:https://gist.github.com/aunnnn/9a6b4608ae49fe1594dbcabd9e607834

答案 1 :(得分:1)

您并不需要Applmusic内的嵌套结构Response。这将完成这项工作:

import Foundation

let json = """
{
    "applmusic":{
        "code":"AAPL",
        "quality":"good",
        "line":"She told me don't worry"
    },
    "I don't want this":"potatoe",
}
"""

public struct Applmusic: Codable {
    public let code: String
    public let quality: String
    public let line: String
}

public struct Response: Codable {
    public let applmusic: Applmusic
}

if let data = json.data(using: .utf8) {
    let value = try! JSONDecoder().decode(Response.self, from: data).applmusic
    print(value) // Applmusic(code: "AAPL", quality: "good", line: "She told me don\'t worry")
}

编辑:处理您的最新评论

如果JSON响应会以嵌套applmusic标记的方式发生更改,则只需要正确更改Response类型即可。例如:

新JSON(请注意,applmusic现在嵌套在新的responseData代码中):

{
    "responseData":{
        "applmusic":{
            "code":"AAPL",
            "quality":"good",
            "line":"She told me don't worry"
        },
        "I don't want this":"potatoe",
    }   
}

唯一需要改变的是Response

public struct Response: Decodable {

    public let applmusic: Applmusic

    enum CodingKeys: String, CodingKey {
        case responseData
    }

    enum ApplmusicKey: String, CodingKey {
        case applmusic
    }

    public init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)

        let applmusicKey = try values.nestedContainer(keyedBy: ApplmusicKey.self, forKey: .responseData)
        applmusic = try applmusicKey.decode(Applmusic.self, forKey: .applmusic)
    }
}

以前的更改不会破坏任何现有代码,我们只是微调Response解析JSON数据以正确获取Applmusic对象的私有实现。 JSONDecoder().decode(Response.self, from: data).applmusic等所有来电都会保持不变。

提示

最后,如果你想完全隐藏Response包装逻辑,你可能有一个公开/公开的方法可以完成所有的工作;如:

// (fine-tune this method to your needs)
func decodeAppleMusic(data: Data) throws -> Applmusic {
    return try JSONDecoder().decode(Response.self, from: data).applmusic
}

隐藏Response甚至存在的事实(将其设为私有/无法访问),可让您通过应用调用decodeAppleMusic(data:)来获取所有代码。例如:

if let data = json.data(using: .utf8) {
    let value = try! decodeAppleMusic(data: data)
    print(value) // Applmusic(code: "AAPL", quality: "good", line: "She told me don\'t worry")
}

推荐阅读:

编码和解码自定义类型

https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types

答案 2 :(得分:0)

有趣的问题。我知道这是2周前,但我很想知道 如何使用我创建的库KeyedCodable来解决它。这是我的通用命题:

struct Response<Type>: Codable, Keyedable where Type: Codable {

    var responseObject: Type!

    mutating func map(map: KeyMap) throws {
        try responseObject <-> map[map.userInfo.keyPath]
    }

    init(from decoder: Decoder) throws {
        try KeyedDecoder(with: decoder).decode(to: &self)
    }
}

帮助程序扩展名:

private let infoKey = CodingUserInfoKey(rawValue: "keyPath")!
extension Dictionary where Key == CodingUserInfoKey, Value == Any {

   var keyPath: String {
        set { self[infoKey] = newValue }

        get {
            guard let key = self[infoKey] as? String else { return "" }
            return key
        }
    }

使用:

let decoder = JSONDecoder()
decoder.userInfo.keyPath = "applmusic"
let response = try? decoder.decode(Response<Applmusic>.self, from: jsonData)

请注意,keyPath可能嵌套得更深,我的意思是它可能是例如。 “responseData.services.applemusic”。

此外,Response是一个Codable,因此您无需任何额外工作即可对其进行编码。