C# json乱码转中文 已测试

本文提供了几种实用的方法来实现中文与Unicode之间的相互转换,包括符合JavaScript规则的转换方式。通过这些方法可以解决API获取到的中文乱码问题,并提供源代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用API得到的数据包括中文,得到的中文是unicode编码,即看到的是乱码,将其转为正常的中文使用以下第三条,其余的是相反情况。

        1./// <summary>

        /// 中文转unicode
        /// </summary>
        /// <returns></returns>
        public static string unicode_0(string str)
        {
            string outStr = "";
            if (!string.IsNullOrEmpty(str))
            {
                for (int i = 0; i < str.Length; i++)
                {
                    outStr += "/u" + ((int)str[i]).ToString("x");
                }
            }
            return outStr;
        }

<span style="white-space:pre">	</span>2.
        /// <summary>
        /// unicode转中文
        /// </summary>
        /// <returns></returns>
        public static string unicode_1(string str)
        {
            string outStr = "";  
            if (!string.IsNullOrEmpty(str))  
            {  
                string[] strlist = str.Replace("/","").Split('u');  
                try  
                {  
                    for (int i = 1; i < strlist.Length; i++)  
                    {  
                        //将unicode字符转为10进制整数,然后转为char中文字符  
                        outStr += (char)int.Parse(strlist[i], System.Globalization.NumberStyles.HexNumber);  
                    }  
                }  
                catch (FormatException ex)  
                {  
                    outStr = ex.Message;  
                }  
            }
            return outStr;
        }

<span style="white-space:pre">	</span>3.
        /// <summary>
        /// unicode转中文(符合js规则的)
        /// </summary>
        /// <returns></returns>
        public static string unicode_js_1(string str)
        {
            string outStr = "";
            Regex reg = new Regex(@"(?i)\\u([0-9a-f]{4})");
            outStr = reg.Replace(str, delegate(Match m1)
            {
                return ((char)Convert.ToInt32(m1.Groups[1].Value, 16)).ToString();
            });
            return outStr;
        }

<span style="white-space:pre">	</span>4.
        /// <summary>
        /// 中文转unicode(符合js规则的)
        /// </summary>
        /// <returns></returns>
        public static string unicode_js_0(string str)
        {
            string outStr = "";
            string a = "";
            if (!string.IsNullOrEmpty(str))
            {
                for (int i = 0; i < str.Length; i++)
                {
                    if (Regex.IsMatch(str[i].ToString(), @"[\u4e00-\u9fa5]")) { outStr += "\\u" + ((int)str[i]).ToString("x"); }
                    else { outStr += str[i]; }
                }
            }
            return outStr;
        } 






                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值