如何从Decodable获取utf8解码字符串? [英] How to get utf8 decoded string from Decodable?
问题描述
问题是我有一个json数据包含和编码的字符串,例如:
The issue is that I have a json data contains and encoded string, example:
let jsonData = "{ \"encoded\": \"SGVsbG8gV29ybGQh\" }".data(using: .utf8)
我需要获取"SGVsbG8gV29ybGQh"字符串的解码值.
What I need is to get the decoded value of "SGVsbG8gV29ybGQh" string.
实际上,我可以通过执行以下操作来获得所需的输出:
Actually I could get the desired output by implementing:
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!
}
我要做的是:
-
将我从json(
result.encoded
)获得的编码字符串转换为数据对象
convert the encoded string That I got from the json (
result.encoded
) to Data object
再次将数据对象转换为字符串.
Reconvert the data object to a string again.
但是,这似乎不仅仅是一个步骤,在这种情况下是否有更好的方法可循?
However, it seems to be more than just a one step to achieve it, is there better approach(es) to be followed for such a case?
推荐答案
在处理Decodable
的编码字符串时,实际上您甚至不必将属性声明为String
,只需直接声明它即可为Data
.
When it comes to handle encoded string for a Decodable
, actually you don't even have to declare the property as String
, just directly declare it as Data
.
因此,对于您的情况,您应该将encoded
编辑为:
So for your case, what you should do is to edit encoded
to as:
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
请记住,这与处理可解码项的日期非常相似,例如,请考虑以下json数据:
Keep in mind that it is a pretty similar case to handling Dates for decodables, as an example consider that we have the following json data:
let jsonData = "{ \"timestamp\": 1527765459 }".data(using: .utf8)
很显然,您不会收到timestamp
作为数字并将其转换为Date对象,而是将其声明为Date
:
Obviously, you won't receive timestamp
as number and convert it to a Date object, instead you would declare it as 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
这篇关于如何从Decodable获取utf8解码字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!