总之,我检索了一个 HTTP Web 响应,其中包含带有 unicode 字符的 JSON 格式数据,例如“\u00c3\u00b1”,应该转换为“ñ”。相反,我正在使用的 JSON 解析器将这些字符转换为“ñ”。我正在寻找的行为是将这些字符转换为“ñ”。
获取以下代码并执行它...
string nWithAccent = "\u00c3\u00b1";
Encoding iso = Encoding.GetEncoding("iso8859-1");
byte[] isoBytes = iso.GetBytes(nWithAccent);
nWithAccent = Encoding.UTF8.GetString(isoBytes);
nWithAccent 输出“ñ”。这是我正在寻找的结果。我采用了上面的代码并将其用于下面的“response_body”变量,该变量包含与上面相同的字符(从我使用 Visual Studio 2008 文本分析器看到的)并且没有得到相同的结果......它与字符“\u00c3\u00b1”。
在我的应用程序中,我针对以 JSON 格式检索数据的外部系统执行以下代码。在 Visual Studio 中使用文本分析器检查“response_body”变量时,我看到“\u00c3\u00b1”而不是ñ。例如,单词“niño”将在文本分析器中显示为“ni\u00c3\u00b1o”。
using (HttpWResponse = (HttpWebResponse)this.HttpWRequest.GetResponse())
{
using (StreamReader reader = new StreamReader(HttpWResponse.GetResponseStream(), Encoding.UTF8))
{
// token will expire 60 min from now.
this.TimeTillTokenExpiration = DateTime.Now.AddMinutes(60);
// read response data
response_body = reader.ReadToEnd();
}
}
然后,我使用开源 JSON 解析器将“\u00c3”替换为“Ô,将“\u00b1”替换为“±”,最终结果为“ñ”而不是“ñ”。JSON解析器有问题还是我对响应流应用了错误的编码?响应中的标头指示字符集为 UTF-8。感谢您的回复!