来自http的c#json数组响应变得乱码

时间:2013-11-06 22:10:12

标签: c# json

我正在尝试从API获取信息,这会在JSON数组中返回结果。

这是我的代码:

string sURL = "http://api.planets.nu/games/list?limit=1";
WebRequest wrGetURL = WebRequest.Create(sURL);
StreamReader objReader = new StreamReader(wrGetURL.GetResponse().GetResponseStream());
string sLine;
sLine = objReader.ReadToEnd();
Console.WriteLine(sLine);

在firefox中粘贴URL时,我会以纯文本形式显示:

[{"name":"Upikarium Sector","description":"This is a battle for the Upikarium Sector. This is a default configuration game. Custom map. This game has 2 turns per week.","shortdescription":"","status":2,"datecreated":"8\/28\/2011 10:11:28 PM","dateended":"1\/1\/0001 12:00:00 AM","maptype":2,"gametype":2,"wincondition":1,"difficulty":1.07299030764822,"tutorialid":0,"requiredlevelid":0,"maxlevelid":0,"masterplanetid":467,"quadrant":23,"mintenacity":0,"faststart":0,"turnsperweek":2,"yearstarted":8,"isprivate":false,"scenarioid":0,"createdby":"none","turn":229,"slots":11,"turnstatus":"xx3x_67x___","hostdays":"_M___F_","slowhostdays":"","hosttime":"18:3","lastbackuppath":"c:\\planetsdata\\backups\\game22158\\turn228-635191849885449557.zip","nexthost":"11\/8\/2013 6:03:00 PM","allturnsin":false,"lastnotified":false,"ishosting":false,"lastloadeddate":"11\/6\/2013 9:16:22 PM","deletedate":"","lasthostdate":"11\/4\/2013 6:04:49 PM","password":"","haspassword":false,"statusname":"Running","timetohost":"Next turn in 44 hours","id":22158}]

这是我应该用我的代码得到的。一个数组,其中一个对象包含游戏信息。

然而,来自writeline的结果是一堆乱码。我似乎无法得到适当的文字结果。我已经打破了一段时间,但无法弄清楚原因。它可能与返回是一个JSON数组有关,因为对返回JSON字典的API的get调用会产生完全可读的文本。但是,这不是一个可读的字符串!

我很确定我错过了一些简单的东西,但它不会找到我!

2 个答案:

答案 0 :(得分:3)

正如文档中所述,内容是gzip压缩,添加对System.IO.Compression的引用并使用以下代码:

 string sURL = "http://api.planets.nu/games/list?limit=1";
 HttpWebRequest wrGetURL = (HttpWebRequest)WebRequest.Create(sURL);
 wrGetURL.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
 StreamReader objReader = new StreamReader(wrGetURL.GetResponse().GetResponseStream(), Encoding.UTF8);
 string sLine;
 sLine = objReader.ReadToEnd();
 Console.WriteLine(sLine);

答案 1 :(得分:0)

这是压缩内容。解决这个问题最简单的方法是添加

wrGetURL.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

在收到回复之前。

希望这有帮助,