Alamofire 4和JSON中的特殊字符

时间:2022-04-26 15:27:19

I've got a problem with special characters with Alamofire 4.
The JSON contains æ, ø and å and the browser shows them fine, also my previous solution using SwiftyJSON did.

Alamofire 4 shows something like this instead:

我对Alamofire 4中的特殊角色有意见。JSON包含æ,ø和浏览器显示他们好,也使用SwiftyJSON做我以前的解决方案。Alamofire 4则显示了如下内容:

U00e6

Using this call:

使用这个调用:

Alamofire.request(specificURL, method: .get, parameters: param, encoding: URLEncoding.default, headers: nil).responseJSON { (response: DataResponse<Any>) in
    print(response)
}

What to do to solve this?

如何解决这个问题?

4 个解决方案

#1


7  

Edit:

编辑:

Alamofire.request(url, method: .get, parameters: param, encoding: JSONEncoding.default)
        .responseJSON { response in

            switch response.result {
            case .success(let value) :

                print(response.request)  // original URL request
                print(response.response) // HTTP URL response
                print(response.data)     // server data
                print(response.result)   // result of response serialization

                if let JSON = response.result.value as! [String:AnyObject]!{
                    print("JSON: ",JSON)
                    self.arrUser = Mapper<Users>().mapArray(JSONArray:JSON["user"] as! [[String : Any]])!
                    self.tableView.reloadData()
                }
            case .failure(let encodingError):
                //Print error
            }
    }

I got the issue that I have added æ in json response and try to print.

我有问题,我添加了æjson响应并试着打印。

Output:

输出:

JSON:  Optional(<__NSArrayI 0x600000050320>(
{
    "email_address" = "testwts06@gmail.com";
     username = "testwts06 \U00e6";
},
{
    "email_address" = "testwts01@gmail.com";
    username = "testwts01 \U00eb";
},
{
    "email_address" = "testwts100@gmail.com";
    username = testwts100;
})

While displaying it display in correct format.

同时以正确的格式显示。

Alamofire 4和JSON中的特殊字符

#2


2  

Seems the typical serialization error due to wrong JSON encoding, probably your response status code is 3840.

看起来典型的序列化错误是由于错误的JSON编码,可能您的响应状态代码是3840。

JSON text SHALL be encoded in UTF-8, UTF-16, or UTF-32.

JSON文本应该用UTF-8、UTF-16或UTF-32编码。

You could try to convert the response data to correct UTF8 encoding:

您可以尝试将响应数据转换为正确的UTF8编码:

let datastring = NSString(data: response.data!, encoding: String.Encoding.isoLatin1.rawValue)
let data = datastring!.data(using: String.Encoding.utf8.rawValue)
do {
     let object = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
     let jsonDic = object as! NSDictionary
     print("  ok, successfully converted..\(jsonDic)")
} catch let aError as Error {
     // print and handle aError 
}

Hope it helps you.

希望它能帮助你。

#3


1  

Swift 3 update for Ekta's answer:

Swift 3更新:

let encodedURL = specificURL.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)

#4


-1  

Here is a simple String extension that solves the issue:

这里有一个简单的字符串扩展来解决这个问题:

extension String {
    func fixUnicode() -> String {
        var copy = self as NSString
        let regex = try! NSRegularExpression(pattern: "\\\\U([A-Z0-9]{4})", options: .caseInsensitive)
        let matches = regex.matches(in: self, options: [], range: NSMakeRange(0, characters.count)).reversed()
        matches.forEach {
            let char = copy.substring(with: $0.rangeAt(1))
            copy = copy.replacingCharacters(in: $0.range, with: String(UnicodeScalar(Int(char, radix: 16)!)!)) as NSString
        }
        return copy as String
    }
}

#1


7  

Edit:

编辑:

Alamofire.request(url, method: .get, parameters: param, encoding: JSONEncoding.default)
        .responseJSON { response in

            switch response.result {
            case .success(let value) :

                print(response.request)  // original URL request
                print(response.response) // HTTP URL response
                print(response.data)     // server data
                print(response.result)   // result of response serialization

                if let JSON = response.result.value as! [String:AnyObject]!{
                    print("JSON: ",JSON)
                    self.arrUser = Mapper<Users>().mapArray(JSONArray:JSON["user"] as! [[String : Any]])!
                    self.tableView.reloadData()
                }
            case .failure(let encodingError):
                //Print error
            }
    }

I got the issue that I have added æ in json response and try to print.

我有问题,我添加了æjson响应并试着打印。

Output:

输出:

JSON:  Optional(<__NSArrayI 0x600000050320>(
{
    "email_address" = "testwts06@gmail.com";
     username = "testwts06 \U00e6";
},
{
    "email_address" = "testwts01@gmail.com";
    username = "testwts01 \U00eb";
},
{
    "email_address" = "testwts100@gmail.com";
    username = testwts100;
})

While displaying it display in correct format.

同时以正确的格式显示。

Alamofire 4和JSON中的特殊字符

#2


2  

Seems the typical serialization error due to wrong JSON encoding, probably your response status code is 3840.

看起来典型的序列化错误是由于错误的JSON编码,可能您的响应状态代码是3840。

JSON text SHALL be encoded in UTF-8, UTF-16, or UTF-32.

JSON文本应该用UTF-8、UTF-16或UTF-32编码。

You could try to convert the response data to correct UTF8 encoding:

您可以尝试将响应数据转换为正确的UTF8编码:

let datastring = NSString(data: response.data!, encoding: String.Encoding.isoLatin1.rawValue)
let data = datastring!.data(using: String.Encoding.utf8.rawValue)
do {
     let object = try JSONSerialization.jsonObject(with: data!, options: .allowFragments)
     let jsonDic = object as! NSDictionary
     print("  ok, successfully converted..\(jsonDic)")
} catch let aError as Error {
     // print and handle aError 
}

Hope it helps you.

希望它能帮助你。

#3


1  

Swift 3 update for Ekta's answer:

Swift 3更新:

let encodedURL = specificURL.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)

#4


-1  

Here is a simple String extension that solves the issue:

这里有一个简单的字符串扩展来解决这个问题:

extension String {
    func fixUnicode() -> String {
        var copy = self as NSString
        let regex = try! NSRegularExpression(pattern: "\\\\U([A-Z0-9]{4})", options: .caseInsensitive)
        let matches = regex.matches(in: self, options: [], range: NSMakeRange(0, characters.count)).reversed()
        matches.forEach {
            let char = copy.substring(with: $0.rangeAt(1))
            copy = copy.replacingCharacters(in: $0.range, with: String(UnicodeScalar(Int(char, radix: 16)!)!)) as NSString
        }
        return copy as String
    }
}