在C#中,如何将一种编码的字符串转换成另外一种编码。

当向服务器发送请求,然后获得返回的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));

这样,不管返回的是什么类型的编码,都能够根据自身的编码类型进行正确的转换了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值