转载:http://www.cnblogs.com/wintersun/archive/2012/09/14/2684708.html
在Visual Studio 2012中轻松把JSON数据转换到POCO的代码,首先你需要安装Web Essentials 2012。在VS2012中,任何cs文件中单击右键就出现这样的菜单:
以这个 http://channel9.msdn.com/niners/CapSoft/achievements/visualstudio?json=true&raw=true URL为示例, 请求后将返回JSON数据:
{"Name":"CapSoft","FriendlyName":"JPHellemons","Achievements":[{"Name":"MoreThan10StepOver","CurrentNumber":11,"DateEarned":"2012-08-22T14:00:23.9742427+02:00"},{"Name":"UsedOrganizedUsings50Achievement","CurrentNumber":3},{"Name":"Regions10Achievement","DateEarned":"2012-01-19T16:04:10.7662105+01:00"},{"Name":"CloseAllButThis10Achievement","CurrentNumber":8},{"Name":"MoreThan10StepInto","CurrentNumber":11,"DateEarned":"2012-08-22T14:00:21.8049672+02:00"},{"Name":"ExtensionsAchievement5","DateEarned":"2012-03-15T09:37:43.3473414+01:00"},{"Name":"ExtensionsAchievement10","DateEarned":"2012-03-15T09:37:43.5283517+01:00"},{"Name":"InstallAndRegisterForAchievements","DateEarned":"2012-03-15T09:37:43.7173626+01:00"},{"Name":"BraveNewWorldAchievement","DateEarned":"2012-08-22T14:43:54.1176689+02:00"},{"Name":"ReferencedAssemblies25","DateEarned":"2012-08-22T14:44:54.1723276+02:00"},{"Name":"MoreThan1000LOC","DateEarned":"2012-08-23T09:39:37.8062693+02:00"},{"Name":"MoreThan30EnumFieldsAchievement","DateEarned":"2012-08-23T09:39:44.3466433+02:00"},{"Name":"LongerThan300LocAchievement","DateEarned":"2012-08-23T09:39:44.6546610+02:00"},{"Name":"EqualOpportunistAchievement","DateEarned":"2012-08-23T09:39:44.7196647+02:00"},{"Name":"GotoAchievement","DateEarned":"2012-08-28T09:55:57.0744434+02:00"},{"Name":"MoreThan10OverloadsAchievement","DateEarned":"2012-08-29T15:08:46.8305656+02:00"}]}
COPY这些数据剪贴版,执行 “Paste JSON as Classes”, 在IDE中我们马上生成这样的代码:
public class Achievement
{
public string Name { get; set; }
public int CurrentNumber { get; set; } public DateTime DateEarned { get; set; }
}
public class Parent
{
public string Name { get; set; }
public string FriendlyName { get; set; } public Achievement[] Achievements { get; set; }
}
我们还没写任何代码,接下来我们从Nuget安装一个JSON.NET的类库,用写下面三行代码就轻易获得数据对象:
WebClient wc = new WebClient();
string json = wc.DownloadString("http://channel9.msdn.com/niners/CapSoft/achievements/visualstudio?json=true&raw=true");
var data = JsonConvert.DeserializeObject<Parent>(json);
好了,到这里为止,由此可见我们编码越来越轻松了,实际上我们还可以处理JSONP的数据,希望对您开发有帮助。
时间: 2024-11-10 13:30:30