当向服务器发送请求,然后获得返回的JSON的时候,字符串的编码可能不是我们想要的。比如返回的如果是GB2132,在C#里可能会是乱码。这时候,我们需要转码,比如把GB2132转成UTF-8。
下面函数TransferStr用来完成转码,Test函数进行调用演示。
private void Test()
{
Encoding strUtf8 = Encoding.UTF8;
Encoding strGb2312 = Encoding.GetEncoding("GB2312");
string str = "测试";// Suppose str is a GB2312 string
str = TransferStr(str, strGb2312, strUtf8);
Console.WriteLine(str);
}
private string TransferStr(string str, Encoding originalEncode, Encoding targetEncode)
{
try
{
byte[] unicodeBytes = originalEncode.GetBytes(str);
byte[] asciiBytes = Encoding.Convert(originalEncode, targetEncode, unicodeBytes);
char[] asciiChars = new char[targetEncode.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
targetEncode.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
string result = new string(asciiChars);
return result;
}
catch
{
Console.WriteLine("There is an exception.");
return "";
}
}
最后输出不再是乱码。
另外,如果你的代码里用StreamReader来处理HttpWebResponse,最好使用这个版本的构造函数:
StreamReader(Stream stream, Encoding encoding);
使用例子如下:
//response's type is HttpWebResponse
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet));
这样,不管返回的是什么类型的编码,都能够根据自身的编码类型进行正确的转换了。
本文介绍了一种在C#中实现字符串从GB2312到UTF-8编码转换的方法,并提供了具体的代码示例。此外,还讨论了如何正确处理HTTP响应中的不同编码。
391

被折叠的 条评论
为什么被折叠?



