json - 如何在 Swift 中显示间接给定的 unicode 字符?

标签 json swift unicode

在 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/

相关文章:

php - 让php输出不带引号的Json,以便javascript将其视为对象

json - 以 JSON 格式打印出 MongoDB 文档

php - 使用 JSON 从数据库中获取信息

swift - 无法覆盖 NSTableViewRow draw() 行为以在 NSOutlineView 中透明

Python unicode 转义下划线和双引号

python - Unicode API 响应抛出错误 '' ascii' 编解码器无法编码字符 u'\u201 9' in position 22462'

c# - 如何调用不带参数的c#方法并访问返回的数据?

ios - bool 值、常量和@IBAction 选择器的 Swift 命名约定?

ios - 获取电子邮件并命名 Facebook SDK v4.4.0 Swift

javascript - 使用 jsPDF 在 pdf 中添加 Unicode 文本