如何从 Decodable 获取 utf8 解码字符串?

How to get utf8 decoded string from Decodable?

问题是我有一个 json 数据包含和编码字符串,例如:

let jsonData = "{ \"encoded\": \"SGVsbG8gV29ybGQh\" }".data(using: .utf8)

我需要的是获取"SGVsbG8gV29ybGQh"字符串的解码值。

实际上我可以通过实现得到想要的输出:

let decoder = JSONDecoder()
let result = try! decoder.decode(Result.self, from: jsonData!)

if let data = Data(base64Encoded: result.encoded), let decodedString = String(data: data, encoding: .utf8) {
    print(decodedString) // Hello World!
}

我要做的是:

但是,实现起来似乎不止一步,对于这种情况,是否有更好的方法可以遵循?

在处理Decodable的编码字符串时,其实你甚至不必将属性声明为String,直接声明为[=17即可=].

所以对于你的情况,你应该做的是将 encoded 编辑为:

struct Result: Decodable {
    var encoded: Data
}

因此:

let decoder = JSONDecoder()
let result = try! decoder.decode(Result.self, from: jsonData!)

let decodedString = String(data: result.encoded, encoding: String.Encoding.utf8)
print(decodedString ?? "") // decodedString

请记住,这与处理可解码的 Dates 非常相似,例如考虑我们有以下 json 数据:

let jsonData = "{ \"timestamp\": 1527765459 }".data(using: .utf8)

显然,您不会收到 timestamp 作为数字并将其转换为 Date 对象,而是将其声明为 Date:

struct Result: Decodable {
    var timestamp: Date
}

因此:

let decoder = JSONDecoder()
// usually, you should edit decoding strategy for the date to get the expected result:
decoder.dateDecodingStrategy = .secondsSince1970

let result = try! decoder.decode(Result.self, from: jsonData!)
print(result.timestamp) // 2018-05-31 11:17:39 +0000