美文网首页
Swift 解析的json中unicode的问题(\u)

Swift 解析的json中unicode的问题(\u)

作者: 太平洋_cfd2 | 来源:发表于2023-01-30 10:18 被阅读0次

    https://www.jianshu.com/p/ea99580ea30f

    func mapJSON(failsOnEmptyData: Bool = true) throws -> Any {
            do {
    //            return try JSONSerialization.jsonObject(with: data, options: .allowFragments)
                do {
                        if let str = String(data: data, encoding: .utf8)
                        {
                            guard let transformStr = str.applyingTransform(StringTransform(rawValue: "Any-Hex/Java"), reverse: true) else {
                                return NSNull()
                            }
                            let data = transformStr.data(using: .utf8)
                            do {
                                let obj = try JSONSerialization.jsonObject(with: data!, options: .fragmentsAllowed)
                                return obj
                            } catch {
                                throw MoyaError.jsonMapping(self)
                            }
                        }
                        
                    } catch  {
                        throw MoyaError.jsonMapping(self)
                    }
            } catch {
                if data.count < 1 && !failsOnEmptyData {
                    return NSNull()
                }
                throw MoyaError.jsonMapping(self)
            }
            throw MoyaError.jsonMapping(self)
        }
    
    func unicodeString(_ str: String) -> String {
        let mutableStr = NSMutableString(string: str) as CFMutableString
        CFStringTransform(mutableStr, nil, "Any-Hex/Java" as CFString, true)
        return mutableStr as String
    }
    
    1. 先将data转string,然后转unicode,最后转utf8
    2. 再json解析就可

    相关文章

      网友评论

          本文标题:Swift 解析的json中unicode的问题(\u)

          本文链接:https://www.haomeiwen.com/subject/ocsmhdtx.html