将文本转换为Unicode字符串

4

我需要处理像这样的JSON文件:

\u0432\u043b\u0430\u0434\u043e\u043c <b>\u043f\u0443\u0442\u0438\u043c<\/b> \u043d\u0430\u0447

很遗憾,我不确定这种编码叫什么名字。

我想将其转换为.NET Unicode字符串。最简单的方法是什么?

1个回答

2

这是俄语字母的Unicode字符。 尝试将这行代码简单地放入VisualStudio中,它会解析它。

string unicodeString = "\u0432\u043b\u0430\u0434\u043e\u043c";

或者如果您想将此字符串转换为另一种编码,比如utf8,请尝试以下代码:

static void Main()
    {
        string unicodeString = "\u0432\u043b\u0430\u0434\u043e\u043c <b>\u043f\u0443\u0442\u0438\u043c<\b> \u043d\u0430\u0447";
        // Create two different encodings.
        Encoding utf8 = Encoding.UTF8;
        Encoding unicode = Encoding.Unicode;

        // Convert the string into a byte[].
        byte[] unicodeBytes = unicode.GetBytes(unicodeString);

        // Perform the conversion from one encoding to the other.
        byte[] utf8Bytes = Encoding.Convert(unicode, utf8, unicodeBytes);

        // Convert the new byte[] into a char[] and then into a string.
        // This is a slightly different approach to converting to illustrate
        // the use of GetCharCount/GetChars.
        char[] asciiChars = new char[utf8.GetCharCount(utf8Bytes, 0, utf8Bytes.Length)];
        utf8.GetChars(utf8Bytes, 0, utf8Bytes.Length, asciiChars, 0);
        string asciiString = new string(asciiChars);

        // Display the strings created before and after the conversion.
        Console.WriteLine("Original string: {0}", unicodeString);
        Console.WriteLine("Ascii converted string: {0}", asciiString);
        Console.ReadKey();
    }

代码来源于Convert

(此文为技术翻译,不提供解释)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接