0

我正在尝试从 API 获取信息,该 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}]

这是我应该用我的代码得到的。一个数组,带有一个保存游戏信息的对象。

但是,写入行的结果是一堆乱码。我似乎无法获得正确的文本结果。我已经为此烦恼了一段时间,不知道为什么。这可能与返回的是 JSON 数组有关,因为对返回 JSON 字典的 API 的 get 调用会产生完全可读的文本。但是,这拒绝成为可读字符串!

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

4

2 回答 2

4

如文档中所述,内容已压缩,添加对 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);
于 2013-11-06T22:23:11.330 回答
1

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

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

在你得到回应之前。

希望这可以帮助,

于 2013-11-06T22:29:02.417 回答