How to create JSON string in C# How to create JSON string in C# json json

How to create JSON string in C#

Using Newtonsoft.Json makes it really easier:

Product product = new Product();product.Name = "Apple";product.Expiry = new DateTime(2008, 12, 28);product.Price = 3.99M;product.Sizes = new string[] { "Small", "Medium", "Large" };string json = JsonConvert.SerializeObject(product);

Documentation: Serializing and Deserializing JSON

You could use the JavaScriptSerializer class, check this article to build an useful extension method.

Code from article:

namespace ExtensionMethods{    public static class JSONHelper    {        public static string ToJSON(this object obj)        {            JavaScriptSerializer serializer = new JavaScriptSerializer();            return serializer.Serialize(obj);        }        public static string ToJSON(this object obj, int recursionDepth)        {            JavaScriptSerializer serializer = new JavaScriptSerializer();            serializer.RecursionLimit = recursionDepth;            return serializer.Serialize(obj);        }    }}


using ExtensionMethods;...List<Person> people = new List<Person>{                   new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"},                   new Person{ID = 2, FirstName = "Bill", LastName = "Gates"}                   };string jsonString = people.ToJSON();

Simlpe use of Newtonsoft.Json and Newtonsoft.Json.Linq libraries.

        //Create my object        var myData = new        {            Host = @"",            UserName = "my_username",            Password = "my_password",            SourceDir = "/export/zip/mypath/",            FileName = ""        };        //Tranform it to Json object        string jsonData = JsonConvert.SerializeObject(myData);        //Print the Json object        Console.WriteLine(jsonData);        //Parse the json object        JObject jsonObject = JObject.Parse(jsonData);        //Print the parsed Json object        Console.WriteLine((string)jsonObject["Host"]);        Console.WriteLine((string)jsonObject["UserName"]);        Console.WriteLine((string)jsonObject["Password"]);        Console.WriteLine((string)jsonObject["SourceDir"]);        Console.WriteLine((string)jsonObject["FileName"]);