在 JSON 数据文件中,我有一个像这样的 unicode 字符:
{
”myUnicodeCharacter”: ”\\u{25a1}”
}
我知道如何从 JSON 文件读取数据。当它包含如上表示的字符时,就会出现问题。
我将其读入字符串变量 myUnicodeCharacterString,该变量获取值“\u{25a1}”。顺便说一下,我无法在 JSON 数据文件中使用单个斜杠,因为在这种情况下,它无法将文件中的数据识别为正确的 JSON 对象,从而返回 nil。
但是,当将值分配给用于显示它的对象(例如 SKLabelNode)时,该值不会编码为其图形表示形式:
mySKLabelNode.Text = myUnicodeCharacterString // displays ”\u{25a1}” and not a hollow square
问题归结为:
// A: direct approach, does works
let unicodeValueByValue = UnicodeScalar("\u{25a1}") // ”9633”
let c1 = Character(unicodeValueByValue) // ”a hollow square”
// B: indirect approach, this does not work
let myUnicodeString = "\u{25a1}"
let unicodeValueByVariable = UnicodeScalar(myUnicodeString) // Error: cannot find an initialiser
let c2 = Character(unicodeValueByVariable)
那么,如果代码中没有直接给出“\u{xxxx}”格式的 unicode 字符,如何显示它呢?
最佳答案
更好的方法是使用正确的 \uNNNN
转义序列
JSON 中的 Unicode 字符(有关详细信息,请参阅 http://json.org)。
这是由 NSJSONSerialization
自动处理的,您不需要
必须转换十六进制代码。
在您的情况下,JSON 数据应该是
{ "myUnicodeCharacter" : "\u25a1" }
Here is a full self-contained example:
let jsonString = "{ \"myUnicodeCharacter\" : \"\\u25a1\"}"
println(jsonString)
// { "myUnicodeCharacter" : "\u25a1"}
let dict = NSJSONSerialization.JSONObjectWithData(jsonString.dataUsingEncoding(NSUTF8StringEncoding)!,
options: nil, error: nil) as [String : String]
let myUnicodeCharacterString = dict["myUnicodeCharacter"]!
println(myUnicodeCharacterString)
// □
关于json - 如何在 Swift 中显示间接给定的 unicode 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56636829/