更新Alamofire后,responseString里的中文乱码。

这是抓包的json:

{
    "buyer": {
        "tmallMemberLevel": 0
    },
    "consumerProtection": {
        "items": [{
            "desc": "ÕýÆ·±£ÕÏ£¬¼ÙÒ»ÅâËÄ",
            "title": "¼ÙÒ»ÅâËÄ",
            "type": 0
        }, {
            "desc": "³ÏÐÅÓû§ÔÚÍË»õ¼Ä³öºó£¬ÏíÊܼ«ËÙÍË¿îµ½ÕË",
            "title": "¼«ËÙÍË¿î",
            "type": 0
        }, {
            "desc": "Âú×ãÏàÓ¦Ìõ¼þʱ£¬Ïû·ÑÕß¿ÉÉêÇë ¡°ÆßÌìÎÞÀíÓÉÍË»»»õ¡±",
            "title": "ÆßÌìÎÞÀíÓÉÍË»»",
            "type": 0
        }],
        "params": "204:3838,2979,2973",
        "passValue": "none",
        "serviceProtection": {
            "basicService": {
                "name": "»ù´¡±£ÕÏ",
                "services": [{
                    "desc": ["ÕýÆ·±£ÕÏ£¬¼ÙÒ»ÅâËÄ"],
                    "icon": "//img.alicdn.com/tfs/TB1_YjSjeL2gK0jSZPhXXahvXXa-54-54.png",
                    "name": "¼ÙÒ»ÅâËÄ"
                }, {

使用 Alamofire 5.0 时,自动对 responseString 的乱码进行了处理:

{"buyer":{"tmallMemberLevel":0},"consumerProtection":{"items":[{"desc":"正品保障,假一赔四","title":"假一赔四","type":0},{"desc":"诚信用户在退货寄出后,享受极速退款到账","title":"极速退款","type":0},{"desc":"满足相应条件时,消费者可申请 “七天无理由退换货”","title":"七天无理由退换",

更新到 Alamofire 5.3,responseString:

{"buyer":{"tmallMemberLevel":0},"consumerProtection":{"items":[{"desc":"ÕýÆ·±£ÕÏ£¬¼ÙÒ»ÅâËÄ","title":"¼ÙÒ»ÅâËÄ","type":0},{"desc":"³ÏÐÅÓû§ÔÚÍË»õ¼Ä³öºó£¬ÏíÊܼ«ËÙÍË¿îµ½ÕË","title":"¼«ËÙÍË¿î","type":0},{"desc":"Âú×ãÏàÓ¦Ìõ¼þʱ£¬Ïû·ÑÕß¿ÉÉêÇë ¡°ÆßÌìÎÞÀíÓÉÍË»»»õ¡±","title":"ÆßÌìÎÞÀíÓÉÍË»»"

如何在不回退的情况下快速处理这个问题?

阅读 3.6k
2 个回答

指定 responseString 的 encoding 为 GBK 编码,系统没有提供,可以自己加一个:

extension String.Encoding {
    
    public static var GB_18030_2000: String.Encoding {
        let cfEncoding = CFStringEncodings.GB_18030_2000
        let resEncoding = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(cfEncoding.rawValue))
        return String.Encoding(rawValue: resEncoding)
    }
    
}
新手上路,请多包涵

调用 responseString 时指定编码方式为 utf-8 就可以了

AF.request(url, parameters: parameters)
    .responseString(encoding: .utf8) {
        code
    }
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏