天天看点

json 中文 unicode 字符解码,unicode 编解码

将  json 中的被(unicode)转义的中文字符还原成中文

如下json:

{“result“:false,“msg“:“\u0043\u0023\u0020\u0075\u006e\u0069\u0063\u006f\u0064\u0065\u0020\u7f16\u7801\u0020\u548c\u0020\u89e3\u7801“,“number“:“124853433“}

在c#中演示如何将以上字符转成中文

1.测试代码段

/// <summary>
        /// C# unicode 编码 和 解码
        /// </summary>
        [TestMethod]
        public void TestUnicode()
        {
            var str = "C# unicode 编码 和 解码";
            var s1 = str.UnicodeEncode();
            var s2 = s1.UnicodeDencode();
            Assert.IsTrue(str == s2);

            string str1 = @"{""result"":false,""msg"":""\u0043\u0023\u0020\u0075\u006e\u0069\u0063\u006f\u0064\u0065\u0020\u7f16\u7801\u0020\u548c\u0020\u89e3\u7801"",""number"":""124853433""}";
            var s3 = str1.UnicodeDencode();
            var s4 = s3;
        }      
public static class StringExtension
    {    
        #region unicode 字符转义
        /// <summary>
        /// 转换输入字符串中的任何转义字符。如:Unicode 的中文 \u8be5
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UnicodeDencode(this string str)
        {
            if (string.IsNullOrWhiteSpace(str))
                return str;
            return Regex.Unescape(str);
        }
        /// <summary>
        /// 将字符串进行 unicode 编码
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string UnicodeEncode(this string str)
        {
            if (string.IsNullOrWhiteSpace(str))
                return str;
            StringBuilder strResult = new StringBuilder();
            if (!string.IsNullOrEmpty(str))
            {
                for (int i = 0; i < str.Length; i++)
                {
                    strResult.Append("\\u");
                    strResult.Append(((int)str[i]).ToString("x4"));
                }
            }
            return strResult.ToString();
        }
        #endregion
    }