VisualStudio2012轻松把JSON数据转换到POCO的代码

本文介绍如何使用Visual Studio 2012中的Web Essentials2012插件快速将JSON数据转换为POCO对象。通过简单的步骤,可以自动生成对应的C#类,并利用JSON.NET轻松解析JSON数据。
摘要由CSDN通过智能技术生成

      在Visual Studio 2012中轻松把JSON数据转换到POCO的代码,首先你需要安装Web Essentials 2012。在VS2012中,任何cs文件中单击右键就出现这样的菜单: 

webessientialRightMenu

  
    以这个 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的数据,希望对您开发有帮助。 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值