我正在尝试从 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 调用会产生完全可读的文本。但是,这拒绝成为可读字符串!
我很确定我错过了一些简单的东西,但它不会影响到我!