Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 897
webmagnets Avatar asked Nov 16 '14 22:11

webmagnets


2 Answers

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.

like image 162
qwerty_so Avatar answered Sep 23 '22 21:09

qwerty_so


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 = 这 是 中文 测试
like image 25
Paul Guyot Avatar answered Sep 23 '22 21:09

Paul Guyot