【问题标题】:How to get utf8 decoded string from Decodable?如何从 Decodable 获取 utf8 解码字符串?
【发布时间】:2018-06-06 00:45:23
【问题描述】:

问题是我有一个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) 得到的编码字符串转换为数据对象

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

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

【问题讨论】:

    标签: swift utf-8 codable


    【解决方案1】:

    在处理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
    

    请记住,这与处理可解码的 日期 非常相似,例如,假设我们有以下 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
    

    【讨论】:

      猜你喜欢
      • 2011-06-13
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      相关资源
      最近更新 更多