美文网首页工作生活
c# unicode转utf8中文

c# unicode转utf8中文

作者: _sands | 来源:发表于2019-07-03 15:48 被阅读0次

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

  1. 首先 unicode中文编码格式都是 \u开头 加四位的16进制Unicode编码
    单个字符转换可以通过 把四位字符串转换成char
// params \u5929
Convert.ToChar(Convert.ToUInt16("5929", 16))

一段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());
}

相关文章

网友评论

    本文标题:c# unicode转utf8中文

    本文链接:https://www.haomeiwen.com/subject/onzqhctx.html