经常在通过httpclient调用远程接口后返回的数据格式的json中包含 unicode编码的中文,也可以手动把其中的unicode中文转化为utf8的中文。
- 首先 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());
}
网友评论