简体   繁体   中英

How can I get the Swift/Xcode console to show Chinese characters instead of unicode?

I am using this code:

import SwiftHTTP    
var request = HTTPTask()
var params = ["text": "这是中文测试"]
request.requestSerializer.headers["X-Mashape-Key"] = "jhzbBPIPLImsh26lfMU4Inpx7kUPp1lzNbijsncZYowlZdAfAD"
request.responseSerializer = JSONResponseSerializer()
request.POST("https://textanalysis.p.mashape.com/segmenter", parameters: params, success: {(response: HTTPResponse) in if let json: AnyObject = response.responseObject { println("\(json)") } },failure: {(error: NSError, response: HTTPResponse?) in println("\(error)") })

The Xcode console shows this as a response:

{
    result = "\U8fd9 \U662f \U4e2d\U6587 \U6d4b\U8bd5";
}

Is it possible to get the console to show the following?:

{
  result = "这 是 中文 分词 测试"
}

If so, what do I need to do to make it happen?

Thanks.

Instead of

println(json)

use

println((json as NSDictionary)["result"]!)

This will print the correct Chinese result.

Reason: the first print will call the debug description for NSDictionary which escapes not only Chinese chars.

Your function actually prints the response object, or more accurately a description thereof. The response object is a dictionary and the unicode characters are encoded with \\Uxxxx in their descriptions.

See question: NSJSONSerialization and Unicode, won't play nicely together

To access the result string, you could do the following:

if let json: AnyObject = response.responseObject {
    println("\(json)")   // your initial println statement
    if let jsond = json as? Dictionary<String,AnyObject> {
        if let result = jsond["result"] as? String {
            println("result = \(result)")
        }
    }
}

The second println statement will print the actual string and this code actually yields:

{
    result = "\U8fd9 \U662f \U4e2d\U6587 \U6d4b\U8bd5";
}
result = 这 是 中文 测试

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM