【问题标题】:How to convert Cookie String to JSON using Swift如何使用 Swift 将 Cookie 字符串转换为 JSON
【发布时间】:2019-03-12 02:31:48
【问题描述】:
   ("Global_Data"): {
       Created = 574049501;
       Domain = "";
       Expires = "2019-03-19 02:11:40 +0000";
       Name = "Data";
       Path = "/";
       Value = "%7B%22countryISO%22%3A%22US%22%2C%22cultureCode%22%3A%22en-GB%22%2C%22currencyCode%22%3A%22USD%22%2C%22apiVersion%22%3A%222.1.4%22%7D;
       Version = 1;
    }

在从 web 视图中获取 Cookie 数据时,我将 Value => 作为字符串 有些字符知道这些字符代表特殊字符或字母。 如何将其转换为 JSON 格式。谢谢

"%7B%22countryISO%22%3A%22US%22%2C%22cultureCode%22%3A%22en-GB%22%2C%22currencyCode%22%3A%22USD%22%2C%22apiVersion%22%3A %222.1.4%22%7D"

【问题讨论】:

    标签: json swift string cookies


    【解决方案1】:

    您的字符串已经是一个 JSON 字符串,您只需从中删除百分比编码,创建一个符合 Decodable 的自定义结构,然后一切就绪:

    struct Root: Decodable {
        let countryISO, cultureCode, currencyCode, apiVersion: String
    }
    

    let string = "%7B%22countryISO%22%3A%22US%22%2C%22cultureCode%22%3A%22en-GB%22%2C%22currencyCode%22%3A%22USD%22%2C%22apiVersion%22%3A%222.1.4%22%7D"
    
    let json = string.removingPercentEncoding ?? ""
    

    "{"countryISO":"US","cultureCode":"en-GB","currencyCode":"USD","apiVersion":"2.1.4"}"

    do {
        let root = try JSONDecoder().decode(Root.self, from: Data(json.utf8))
        print(root.countryISO)    // "US"
        print(root.cultureCode)   // "en-GB"
        print(root.currencyCode)  // "USD"
        print(root.apiVersion)    // "2.1.4"
    } catch {
        print(error) 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-22
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多