How to display indirectly given unicode character in Swift?

前端 未结 2 1749
攒了一身酷
攒了一身酷 2020-12-21 13:01

In a JSON data file, I have a unicode character like this:

{
    ”myUnicodeCharacter”: ”\\\\u{25a1}”
}

I know how to read data from JSON fi

相关标签:
2条回答
  • A better way would be to use the proper \uNNNN escape sequence for Unicode characters in JSON (see http://json.org for details). This is automatically handled by NSJSONSerialization, and you don't have to convert a hex code.

    In your case the JSON data should be

    {
        "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)
    // □
    
    0 讨论(0)
  • 2020-12-21 13:28

    I came up with a solution, which does not answer the question, but is actually a better way of doing what I'm trying to do.

    The unicode character is given instead as its hexadecimal value in the JSON data file, stripping all escape characters:

    {
        ”myUnicodeCharacter”: ”25a1”
    }
    

    Then it's processed like this, after reading the value in to myUnicodeCharacterString:

    let num = Int(strtoul(myUnicodeCharacterString, nil, 16))
    mySKLabelNode.Text = String(UnicodeScalar(num))
    

    And that worked. Now the hollow square showed up.

    0 讨论(0)
提交回复
热议问题