我调查了一下,这里的问题是,您在JSON结果中看到的是编码的 value ,而不是 key 。因此,添加CodingKeys
将无济于事。
稍微复杂的解决方案使用自定义协议和相应的扩展来实现目标。
这样,您可以声明:
enum Test: String,CaseNameCodable {
case one = "Number One"
case two = "Number Two"
}
它将满足您的需求。
下面概述了一个完整的工作示例(在Xcode 11.2的Playground中为我工作):
import Foundation
// A custom error type for decoding...
struct CaseNameCodableError: Error {
private let caseName: String
init(_ value: String) {
caseName = value
}
var localizedDescription: String {
#"Unable to create an enum case named "\#(caseName)""#
}
}
//
// This is the interesting part:
//
protocol CaseNameCodable: Codable,RawRepresentable,CaseIterable {}
extension CaseNameCodable {
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let value = try container.decode(String.self)
guard let raw = Self.allCases.first(where: { $0.caseName == value })?.rawValue else { throw CaseNameCodableError(value) }
self.init(rawValue: raw)!
}
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(caseName)
}
private var caseName: String {
return "\(self)"
}
}
//
// Now you can use the protocol CaseNameCodable just like you
// would use Codable (on RawRepresentable enums only)
//
enum Test: String,CaseNameCodable {
case one = "Number One"
case two = "Number Two"
}
// EXAMPLE:
// Create a test value
let testValue = Test.one
// encode it and convert it to a String
let jsonData = try! JSONEncoder().encode(testValue)
let jsonString = String(data: jsonData,encoding: .utf8)!
print (jsonString) // prints: "one"
// decode the same data to produce a decoded enum instance
let decodedTestValue = try JSONDecoder().decode(Test.self,from: jsonData)
print(decodedTestValue.rawValue) // prints: Number One
本文链接:https://www.f2er.com/3162851.html