代码之家  ›  专栏  ›  技术社区  ›  Ahmad F

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

  •  0
  • Ahmad F  · 技术社区  · 6 年前

    问题是我有一个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!
    }
    

    我要做的是:

    • 转换从json获得的编码字符串( result.encoded )到数据对象

    • 再次将数据对象转换为字符串。

    然而,这似乎不仅仅是实现这一目标的一个步骤,是否有更好的办法来处理这种情况?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Ahmad F    6 年前

    当处理编码字符串时 Decodable ,实际上您甚至不必将该属性声明为 String ,直接声明为 Data .

    所以对于你的案例,你应该做的是编辑 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
    

    请记住,这与处理 日期 对于decodables,作为一个例子,假设我们有以下json数据:

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

    显然,你不会得到 timestamp 作为数字并将其转换为日期对象,而是将其声明为 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