字典的可解码 keyDecodingStrategy 自定义处理

Mar*_*ark 2 json swift codable decodable jsondecoder

我有以下 JSON 对象:

{
  "user_name":"Mark",
  "user_info":{
    "b_a1234":"value_1",
    "c_d5678":"value_2"
  }
}
Run Code Online (Sandbox Code Playgroud)

我已经JSONDecoder这样设置了:

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
Run Code Online (Sandbox Code Playgroud)

我的Decodable对象看起来像这样:

struct User: Decodable {
    let userName: String
    let userInfo: [String : String]
}
Run Code Online (Sandbox Code Playgroud)

我面临的问题是该.convertFromSnakeCase策略正在应用于字典的键,我希望这种情况不会发生。

// Expected Decoded userInfo
{
  "b_a1234":"value_1",
  "c_d5678":"value_2"
}

// Actual Decoded userInfo
{
  "bA1234":"value_1",
  "cD5678":"value_2"
}
Run Code Online (Sandbox Code Playgroud)

我研究过使用自定义keyDecodingStrategy(但没有足够的信息来以不同方式处理字典)以及我的自定义初始值设定项Decodable结构的自定义初始值设定项(似乎此时键已经被转换)。

处理此问题的正确方法是什么(仅为字典创建键转换异常)?

注意:我更愿意保留蛇形大小写转换策略,因为我的实际 JSON 对象在蛇形大小写中有很多属性。我当前的解决方法是使用 CodingKeys 枚举手动进行蛇形大小写转换。

Rob*_*ier 5

是的……但是,这有点棘手,最终添加 CodingKeys 可能会更健壮。但这是可能的,并且对自定义密钥解码策略进行了不错的介绍。

首先,我们需要一个函数来进行蛇形转换。我真的希望它能在 stdlib 中公开,但事实并非如此,而且我不知道有什么方法可以在不复制代码的情况下“到达那里”。这是直接基于JSONEncoder.swift的代码。(我什至不想将其复制到答案中,但否则您将无法重现其余部分。)

// Makes me sad, but it's private to JSONEncoder.swift
// https://github.com/apple/swift/blob/master/stdlib/public/Darwin/Foundation/JSONEncoder.swift
func convertFromSnakeCase(_ stringKey: String) -> String {
    guard !stringKey.isEmpty else { return stringKey }

    // Find the first non-underscore character
    guard let firstNonUnderscore = stringKey.firstIndex(where: { $0 != "_" }) else {
        // Reached the end without finding an _
        return stringKey
    }

    // Find the last non-underscore character
    var lastNonUnderscore = stringKey.index(before: stringKey.endIndex)
    while lastNonUnderscore > firstNonUnderscore && stringKey[lastNonUnderscore] == "_" {
        stringKey.formIndex(before: &lastNonUnderscore)
    }

    let keyRange = firstNonUnderscore...lastNonUnderscore
    let leadingUnderscoreRange = stringKey.startIndex..<firstNonUnderscore
    let trailingUnderscoreRange = stringKey.index(after: lastNonUnderscore)..<stringKey.endIndex

    var components = stringKey[keyRange].split(separator: "_")
    let joinedString : String
    if components.count == 1 {
        // No underscores in key, leave the word as is - maybe already camel cased
        joinedString = String(stringKey[keyRange])
    } else {
        joinedString = ([components[0].lowercased()] + components[1...].map { $0.capitalized }).joined()
    }

    // Do a cheap isEmpty check before creating and appending potentially empty strings
    let result : String
    if (leadingUnderscoreRange.isEmpty && trailingUnderscoreRange.isEmpty) {
        result = joinedString
    } else if (!leadingUnderscoreRange.isEmpty && !trailingUnderscoreRange.isEmpty) {
        // Both leading and trailing underscores
        result = String(stringKey[leadingUnderscoreRange]) + joinedString + String(stringKey[trailingUnderscoreRange])
    } else if (!leadingUnderscoreRange.isEmpty) {
        // Just leading
        result = String(stringKey[leadingUnderscoreRange]) + joinedString
    } else {
        // Just trailing
        result = joinedString + String(stringKey[trailingUnderscoreRange])
    }
    return result
}
Run Code Online (Sandbox Code Playgroud)

我们还想要一把 CodingKey 瑞士军刀,它也应该在 stdlib 中,但实际上不在:

struct AnyKey: CodingKey {
    var stringValue: String
    var intValue: Int?

    init?(stringValue: String) {
        self.stringValue = stringValue
        self.intValue = nil
    }

    init?(intValue: Int) {
        self.stringValue = String(intValue)
        self.intValue = intValue
    }
}
Run Code Online (Sandbox Code Playgroud)

这只是让您将任何字符串转换为 CodingKey。它来自JSONDecoder 文档

最后,这就是所有的样板垃圾。现在我们可以触及它的核心了。没有办法直接说“除了字典中的”。CodingKeys 的解释独立于任何实际的 Decodable。所以你想要的是一个函数,它说“应用蛇形命名法,除非这是嵌套在某某键内的键”。这是一个返回该函数的函数:

func convertFromSnakeCase(exceptWithin: [String]) -> ([CodingKey]) -> CodingKey {
    return { keys in
        let lastKey = keys.last!
        let parents = keys.dropLast().compactMap {$0.stringValue}
        if parents.contains(where: { exceptWithin.contains($0) }) {
            return lastKey
        }
        else {
            return AnyKey(stringValue: convertFromSnakeCase(lastKey.stringValue))!
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,我们只需要一个自定义密钥解码策略(请注意,这使用驼峰式版本的“userInfo”,因为 CodingKey 路径是在应用转换之后):

decoder.keyDecodingStrategy = .custom(convertFromSnakeCase(exceptWithin: ["userInfo"]))
Run Code Online (Sandbox Code Playgroud)

结果:

User(userName: "Mark", userInfo: ["b_a1234": "value_1", "c_d5678": "value_2"])
Run Code Online (Sandbox Code Playgroud)

我不能保证这比仅仅添加 CodingKeys 值得麻烦,但它对于工具箱来说是一个有用的工具。