C#-各种编码字符处理经验汇总

跨系统中或在通过httpclient调用远程接口后返回的数据格式的json中经常包含 unicode编码的中文,手动方式可以把其中的unicode中文转化为utf8的中文。

1、首先 unicode中文编码格式都是 \u开头 加四位的16进制Unicode编码

单个字符转换可以通过 把四位字符串转换成char

// params \u5929
Convert.ToChar(Convert.ToUInt16("5929", 16))

2、一段json 有普通英文字母也有这种unicode编码 可以通过正则找出来并全部替换掉

 public static string ConvertUnicodeToUtf8(this string unicode)
{
      if (string.IsNullOrEmpty(unicode))
      {
                return string.Empty;
      }
      return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled)
                .Replace(unicode, p => Convert.ToChar(Convert.ToUInt16(p.Result("$1"), 16)).ToString());
}
posted @   吴土炮Jared  阅读(97)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示