1 Comments

This blog will show you how to download a JSON string and parse it to POCO objects with Asp.Net C# in Visual Studio 2012 with an extension and nuget package and only 3 lines of code.

For this example I am using the Visual Studio achievements. You can install the extension in Visual Studio 2012 and/or Visual Studio 2010. It uses FxCop and is a lot of fun. So I have installed this extension and have several achievements.

The url for your personal page is:

http://channel9.msdn.com/niners/USERNAME/achievements/visualstudio

I have found the API of the achievements on  and it is using JSON. In my web project I added this NuGet package to work with JSON.

NuGet

To make life easier, I have installed Mads Kristensens Web Essentials 2012.

So I have copied the output of

http://channel9.msdn.com/niners/CapSoft/achievements/visualstudio?json=true&raw=true

and in Visual Studio 2012 I right clicked in the code behind:

image

Paste JSON As Classes!

That gives you (without coding)

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; }
}

To use it, you can use a webclient object to download the JSON string and parse it using newtonsoft.json.

All that with just 3 lines of code!

protected void Page_Load(object sender, EventArgs e)
{
    WebClient wc = new WebClient();
    string json = wc.DownloadString("http://channel9.msdn.com/niners/CapSoft/achievements/visualstudio?json=true&raw=true");
    var a = JsonConvert.DeserializeObject<Parent>(json);
}

Good luck coding!

kick it on DotNetKicks.com Shout it

Pin on pinterest Plus on Googleplus Post on LinkedIn

Comments

Comment by DotNetKicks.com

Use JSON resource in Asp.Net C

You've been kicked (a good thing) - Trackback from DotNetKicks.com