Monday, January 14, 2013

Convert json string to CLR type

In this post I will show you how to convert json string to CLR types using c#


Assembly Required
System.Web.Design

using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
namespace ConsoleApplication1
{
    public class Likes
    {
    public List<Like> data { get; set; }
    }
    public class Like
    {
    public string Category { get; set; }
    public string Name { get; set; }
    public string ID { get; set; }
    public string created_time { get; set; }
    public Like()
        {
        }
    }
    public class Program
    {
    static void Main(string[] args)
        {
    string jsonData = @"{
                                   ""data"": [    {
                               ""category"": ""Community"",
                                ""name"": ""Swati"",
                                ""id"": ""190847514395344"",
                                ""created_time"": ""2013-01-09T07:24:29+0000""
                            },
                            {
                                ""category"": ""Wine/spirits"",
                                ""name"": ""Chill with Rémy, India"",
                                ""id"": ""184640834879687"",
                                ""created_time"": ""2013-01-08T05:41:59+0000""
                            },
                            {
                                ""category"": ""Fictional character"",
                                ""name"": ""MAMU"",
                                ""id"": ""366505623417822"",
                                ""created_time"": ""2012-12-04T17:51:36+0000""
                            }]}";
            JavaScriptSerializer js = new JavaScriptSerializer();
            Likes result = js.Deserialize<Likes>(jsonData);
        }
    }
}