Converting json string to C# object and vice versa
In order to convert a C# generic list to json string and vice versa,
Add reference to System.Web.Extensions in your project.
//Assume that, you have a generic list as shown below,
List<Patient> patientList = GetPatients();
Use Serialize method in JavaScriptSerializer class for serializing generic list to Json string.
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
//use Serialize method to convert patient list to json string
string JStr = serializer.Serialize(patientList);
//Now, the json string can be set to generic list of type patient as shown below,
List<Patient> nList = new List<Patient>();
nList = serializer.Deserialize<List<Patient> >(JStr);
DOWNLOAD the working sample here https://docs.google.com/file/d/0By3at1G2EGgOal9IMW5pQjNTNXM/edit (File->Download)
Hi, I am not able to get the ‘Script’ namespace after System.Web? I am I missing anything at my end? Please suggest.
Comment by Saravana | February 25, 2011 |
Saravana, please add reference to “system.web.extensions” in your project. This will provide JavaScriptSerializer class.
Comment by jgvimalan | February 26, 2011 |
dude this doesn’t work for deserializing 😦
Comment by jj | June 5, 2012 |
Are you getting any error or its not deserializing at all?
Comment by JG Vimalan | June 28, 2012 |
Awesome, this worked exactly as I needed it to for JSON to List, this was a life saver!
Comment by Dan | June 11, 2012 |
perfect one.
Comment by Rajib Nandi | December 18, 2012 |
Very good…please how in {“data”:”1″,rules[{“name”:”Frank”}]}
Comment by Frank | June 22, 2014 |