Convert C# Object to JSON and create object from JSON string

Json.Net is the preferred way to go about it because of performance gain it gets compared to JavascriptSerializer.

Download and install Newtonsoft.Json using Nuget

Now in order to create Json for an object simply use SerializeObject method as following

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };

string json = JsonConvert.SerializeObject(product);
// {
//   "Name": "Apple",
//   "Expiry": "2008-12-28T00:00:00",
//   "Sizes": [
//     "Small"
//   ]
// }

In order to convert Json to the object use DeserializeObject method as following

string json = @"{
  'Name': 'Bad Boys',
  'ReleaseDate': '1995-4-7T00:00:00',
  'Genres': [
    'Action',
    'Comedy'
  ]
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;
// Bad Boys

 


Leave A Comment

Your email address will not be published.