parse json to object c# code example

Example 1: object to json c#

using Newtonsoft.Json;

var jsonString = JsonConvert.SerializeObject(obj);

Example 2: c# parse json

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);
//{
//  "Name": "Apple",
//  "Expiry": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

Example 3: c# convert object to json

var jsonString = JsonConvert.SerializeObject(ObjectModel);

Example 4: js object to c# object

// Construct a object in JS

var obj = {
  id: 0 ,
  userName: 'Bill'
};

// C# class:

public class myClass
{
  public int id;
  public string userName;
}

// Then for example using AJAX send your data to C#,
// and deserialize, when you need work with object

$.ajax({
	type: "POST",
  	// Note that you need to pass the method as url
	url: '<your server url>' + 'DeserializeObject',
  	// your data is the object you want to send
	data: obj,
	contentType: "application/text; charset=utf-8",
	dataType: "text"
})

[HttpPost]
public void DeserializeObject(string objJson)
{
var obj = (new JavascriptSerializer()).Deserialize<myClass>(objJson);
}