Reader Level:
Articles

Conversion from Object to JSON by Json.NET

By Amit Patel on July 02, 2012
Json.NET is a popular high-performance JSON framework for .NET
  • 1
  • 0
  • 24073
Download Files:
 

Json.NET is a popular high-performance JSON framework for .NET

Features
  • Flexible JSON serializer for converting between .NET objects and JSON
  • LINQ to JSON for manually reading and writing JSON
  • High performance, faster than .NET's built-in JSON serializers
  • Write indented, easy to read JSON
  • Convert JSON to and from XML
  • Supports .NET 2, .NET 3.5, .NET 4, Silverlight and Windows Phone
The serializer is a good choice when the JSON you are reading or writing maps closely to a .NET class.

LINQ to JSON is good for situations where you are only interested in getting values from JSON, you don't have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects.

How do we get Json.NET Library. 

We can get it fron NuGet :- https://nuget.org/packages/Newtonsoft.Json

Sample Code

    class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Salary { get; set; }
        public Address Address { get; set; }
    }
    class Address
    {
        public string City { get; set; }
        public int PinCode { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            
            Customer c = new Customer();
            c.Id = 1;
            c.Salary = 1111;
            c.Name = "Amit Patel";
            c.Address = new Address();
            c.Address.City = "Pune";
            c.Address.PinCode = 411078;

            var customer = Newtonsoft.Json.JsonConvert.SerializeObject(c);
            Console.WriteLine(customer);
            Customer c1 = Newtonsoft.Json.JsonConvert.DeserializeObject<Customer>(customer);
            Console.Read();

        }
    }


Happy Coding....


Amit Patel

I am  C# Corner MVP in Q2 2012.  I have 10 years of experiences in Microsoft technologies. I am very much passionate about Web technology. My core skill is ASP.NET, WCF, C#, JQuery and CSS.

COMMENT USING

Trending up