Convert objects to JSON in C# using JavaScriptSerializer

12 במרץ 2009

45 comments

Want to convert a C# object into it's JSON equivalent? Here is a simple object from the System.Web.Script namespace that does exactly that:

System.Web.Script.Serialization.JavaScriptSerializer . It is stored in the System.Web.Extentions DLL (.Net Framework 3.5 only)

Using this object we serialize and deserialize  objects in C#. Here is a quick sample:

A simple Employee object:

public class Employee
{
    public string Name { get; set; }
    public string Age { get; set; }
    public string ID { get; set; }   
}
 

Adding some instances of them to a List:

Employee oEmployee1 = 
       new Employee{Name="Pini",ID="111", Age="30"};

Employee oEmployee2 = 
      new Employee { Name = "Yaniv", ID = "Cohen", Age = "31" };
Employee oEmployee3 = 
        new Employee { Name = "Yoni", ID = "Biton", Age = "20" };

List<Employee> oList = new List<Employee>() 
{ oEmployee1, oEmployee2, oEmployee3 };
 

Serializing then:

System.Web.Script.Serialization.JavaScriptSerializer oSerializer = 
         new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(oList);

And here is the output:

[{"Name":"Pini","Age":"30","ID":"111"},
{"Name":"Yaniv","Age":"31","ID":"Cohen"},
{"Name":"Yoni","Age":"20","ID":"Biton"}]
 
Enjoy. 
Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

45 comments

  1. kris3 ביוני 2009 ב 22:02

    hello,

    thanks for the code. I have a question. Is this available in a windows application as well? I have a windows project ( actually its a addin to Excel) that communicate with a Java application through web services. Can I use the json in a windows application?

    Reply
  2. Pini Dayan9 ביוני 2009 ב 15:18

    Well good question
    I am guessing that the answer is no since my solution is a C# code.

    Reply
  3. sunil15 באוקטובר 2009 ב 5:08

    is there any equivalent class or any other option to use this with the 2.0 framework?

    Reply
  4. Pini Dayan19 באוקטובר 2009 ב 7:20

    Yes. you have 2 option, adding a refenrce to the C# 3 System.Web.Extentions dll or writing your own serializer.

    Reply
  5. Itamar Gigi1 בינואר 2010 ב 21:26

    Hello pini you are great and wonderfull man.
    excellent code.
    you very helped me with this solution.

    Reply
  6. Pini Dayan5 בינואר 2010 ב 9:57

    You welocme.
    Thanks

    Reply
  7. Bill Sternberger26 בפברואר 2010 ב 15:56

    Thanks, this is awesome, you just saved me a bunch of time!!

    Reply
  8. Pini Dayan28 בפברואר 2010 ב 10:20

    You welcome 🙂

    Reply
  9. Conan11 במרץ 2010 ב 11:54

    oh my god! You are a very great man! A very great man, my friend! This worked perfectly the first time on a custom class containing generic lists of custom objects. I wish I would have found you two days ago!

    Righteous!

    Reply
  10. aQuila25 במרץ 2010 ב 17:52

    How will you go about reading the data now.  I tried to make it work (for 8 hours) but nothing. Any Ideas?

    Reply
  11. aQuila26 במרץ 2010 ב 10:12

    Hi Pini,

    I'm an exchange student in Belgium and i saw your blog some days ago.  I gave it a try and everything works perfectly except that i struggled to read the data from the serialized object… Do you have any suggestions?

    Kind Regards,

    aQuila

    Reply
  12. Pini Dayan28 במרץ 2010 ב 11:52

    LOL, Thanks man
    Come again 🙂

    Reply
  13. Pini Dayan28 במרץ 2010 ב 11:52

    LOL, Thanks man
    Come again 🙂

    Reply
  14. Pini Dayan28 במרץ 2010 ב 11:58

    Simply use the Desialize method 🙂
    If you have any question write to my mail i could then answer faster
    Pinid@sela.co.il

    Reply
  15. Jason16 במאי 2010 ב 6:50

    Thanks for putting this up. Here is another suggestion of creating quick objects without having to strongly type them since we are in .net 3.5+ these days.

    Instead of creating an object defined at compile time as the above example shows, create one at runtime.

    For example do this with C#

    var obj = {

     success = true,

     message = "added to db"

    };

    // then do serialize on the obj with Pini's suggestion. This is more akin to how we do javascript so its a more natural way to go and is more flexible for the client-side programmer expecting a certain format.

    Reply
  16. satya17 באוגוסט 2010 ב 16:29

    Thnks to give the Serialization code…

    Can you just show how to deserialize the object what we are getting response from JSON service.

    Reply
  17. Vince11 בספטמבר 2010 ב 1:22

    Thanks a lot! I've been looking for a way to return JSON from my .net WebService for a while! Youre method is so simple, it's exactly what I've been looking for!

    Reply
  18. Akhilesh15 בספטמבר 2010 ב 14:43

    Hi,

    Thanks for the simple demo. Can we serialize an array list of objects having null fields?

    Thanks

    Reply
  19. Shane van Wyk16 בספטמבר 2010 ב 12:08

    Now how do you convert it back to the object?

    Reply
  20. binhvu19 באוקטובר 2010 ב 6:53

    It's easy to deserialize json to objec.
    Please use this part of code

    Employee oEmployee1 = new Employee { Name = "Pini", ID = "111", Age = "30" };

    Employee oEmployee2 = new Employee { Name = "Yaniv", ID = "Cohen", Age = "31" };

    Employee oEmployee3 = new Employee { Name = "Yoni", ID = "Biton", Age = "20" };

    List oList = new List() { oEmployee1, oEmployee2, oEmployee3 };
    System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
    string sJSON = oSerializer.Serialize(oList);

    List newList = oSerializer.Deserialize>(sJSON);
    string nJson = oSerializer.Serialize(newList);

    MessageBox.Show(nJson);

    Reply
  21. ganesh25 באוקטובר 2010 ב 11:04

    hi, using this i could not able to deserialize the json object from android client… what should i do?. for android the response status goes as "OK 200." but for me the insert operation is not performed

    Reply
  22. Ryan Sameie27 בנובמבר 2010 ב 15:57

    My Point is : I hate webforms, i cannot udnerstand it! I dislike webforms, i hate webforms, so, i believe you have to get out of it! this is a complete shitfull design, i like MVC, I love MVC! i am in love with ajax , mvc and so on! why i kill myself with webforms which si much harder than others?

    Reply
  23. Dan Anos30 בנובמבר 2010 ב 19:15

    Is it possible to use this with anonymous types?

    Reply
  24. Thien Le8 במרץ 2011 ב 9:12

    How to due with some characters such as \r\n and \u003e?

    Reply
  25. Hsan15 במרץ 2011 ב 0:42

    how to Dynamic data ?

    Reply
  26. manju24 במרץ 2011 ב 13:36

    helo can i use json in console application.please give u r thoughts.

    http://www.dotnetspider.com/forum/282367-Json-console.aspx

    Reply
  27. Zaguerinho23 באפריל 2011 ב 9:58

    how about putting back the json string into a List variable? is ther a quick way to do that?

    Regards

    jorge.

    Reply
  28. ايفون10 במאי 2011 ב 16:53

    how can i output json instead of xml in c sharp webservice , thanks

    Reply
  29. ايفون10 במאי 2011 ב 16:54

    how can i output json instead of xml in c sharp webservice , thanks

    Reply
  30. Newton11 ביולי 2011 ב 3:39

    Hey, firstly thanks for writing this article and secondly i am just posting this here for whoever wants or needs it. Convert C# object to javascript object code: External .js file contents

    step 1 add this property to your class

    public string PropertiesAsString { get; set;}

    step 2 add this method to your class

    public void BuildPropertiesString()
    {
    foreach (System.Reflection.PropertyInfo property in this.GetType().GetProperties())
    {
    if (property.Name != "PropertiesAsString")
    this.PropertiesAsString += property.Name + ":" + property.PropertyType.Name.ToString() + ":" + property.GetValue(this, null).ToString() + "-";
    if (this.GetType().GetProperties().Last().Name == property.Name)
    this.PropertiesAsString = this.PropertiesAsString.TrimEnd('-');
    }
    }
    step 3 create this .js file

    function convertToJavaObject(cObjectPropertiesAsString) {
    var convertedObject = {};
    var propertiesAndValuesAsArray = cObjectPropertiesAsString.split('-');
    for (var i = 0; i < propertiesAndValuesAsArray.length; i++) { eval("convertedObject." + propertiesAndValuesAsArray[i].split(':')[0] + "Type='" + propertiesAndValuesAsArray[i].split(':')[1] + "'"); eval("convertedObject." + propertiesAndValuesAsArray[i].split(':')[0] + "Value='" + propertiesAndValuesAsArray[i].split(':')[2] + "'"); } return convertedObject; } step 4 reference the file in your webpage i.e

    Now whenever you want to get the c# object properties value all you need to do is call it like this : alert(convertedObject.MyPropertyColorValue);
    and
    alert(convertedObject.MyPropertyColorType); returns the property type like string, datetime etc. I hope someone out there finds this useful ad advice or questions email me on nalanzo2000@yahoo.co.uk

    Reply
  31. Yavuz Yasin CELIK11 באוגוסט 2011 ב 14:51

    /* Tanks for code it was so usefull to create json * data
    */

    //
    public class countrylist : IHttpHandler
    {

    public void ProcessRequest(HttpContext context)
    {
    context.Response.ContentType = "text/plain";

    List arr1 = new List();
    List arr2 = new List();
    JavaScriptSerializer oSerializer = new JavaScriptSerializer();
    DataTable dt = new DataTable();
    string sJSON = "";
    var sql = "";

    try {
    sql = @"select pkcountry, country from lc_country";
    dt = DB.getData(sql);

    foreach(DataRow dr in dt.Rows)
    arr2.Add(new Arr2{id= dr["pkcountry"].ToString(), name=dr["country"].ToString()});

    arr1.Add(new Arr1 { statu = true, count = dt.Rows.Count, data = arr2 });
    sJSON = oSerializer.Serialize(arr1);
    }
    catch (Exception ex) {
    }
    context.Response.Write(sJSON);
    }

    public bool IsReusable
    {
    get
    {
    return false;
    }
    }
    }

    public class Arr1
    {
    public Boolean statu { get; set; }
    public int count { get; set; }
    public List data { get; set; }
    }

    public class Arr2
    {
    public string id { get; set; }
    public string name { get; set; }
    }
    // end of the handler

    //
    function getCountryUnits(fkcountry) {
    var UnitList = $('#fknationality');
    var empOptionlist = document.createElement("option");
    $(empOptionlist).attr("value", "-1");
    $(empOptionlist).html("Loading…");
    $(empOptionlist).css("font-style", "italic");
    UnitList.append(empOptionlist);
    $.ajax({
    url: "func/countrylist.ashx",
    dataType: "json",
    success: function (data) {
    UnitList.empty();
    if (data[0].count > 0) {
    for (var i = 0; i < data[0].count; i++) { var n = data[0].data[i]; var optionlist = document.createElement("option"); $(optionlist).attr("value", n.id); $(optionlist).html(n.name); UnitList.append(optionlist); } if (fkcountry > 0) { UnitList.val(fkcountry); }
    }
    else {
    var empOptionlist = document.createElement("option");
    $(empOptionlist).attr("value", "-1");
    $(optionlist).html(" ");
    UnitList.append(optionlist);
    }
    },
    error: function (data) {
    jAlert("Could not complete process temporarily.", "Data Server");
    }
    });
    }

    // End of the javascript

    Reply
  32. Don29 בספטמבר 2011 ב 0:57

    Thank you so much. I realize that this page is old, but it has been so helpful for me in working on my project. Thank you!

    Reply
  33. Akhtar4 באוקטובר 2011 ב 12:57

    please give help me in solving the exception

    A circular reference was detected while serializing an object of type 'System.Reflection.Module'.

    System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeEnumerable(IEnumerable enumerable, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeCustomObject(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValue(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, StringBuilder output, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj, SerializationFormat serializationFormat)
    at System.Web.Script.Serialization.JavaScriptSerializer.Serialize(Object obj)
    at iPhysioIntel.StagingService.Service1.CodeToRun() in D:\cctproject\iPhysioIntel\StagingService\StagingService\Service1.cs:line 55

    Reply
  34. test11 בנובמבר 2011 ב 14:44

    anyone can do this

    Reply
  35. fh44 בינואר 2012 ב 11:57

    I will try it, thanks.
    There is thie library too: http://json.codeplex.com/

    Reply
  36. PepLamb10 בינואר 2012 ב 20:00

    Awesome example!!!
    ( also supported in .NET 4 and above (4.5) )

    A Question is this library available for Silverlight too?

    Reply
  37. Varun17 בפברואר 2012 ב 14:38

    How to parse this

    "{'123': {'id': '345', 'name': 'Varunsathyam', 'first_name': 'Varun'}}"

    Reply
  38. Niranjan Raju24 בפברואר 2012 ב 7:29

    Hi Pini,

    A perfect solution for my woes :). However, when I serialize the object, the final object has a lot of \" around the key value pair for e.g.:

    "[{\"name\":\"value1"},{\"name\":"\value2\"}]"

    When I run this through JSONLInt for validation, it is recognized as an invalid JSON. any tips on how to get rid of these quotes? BTW: if I do call a REST service with POST method and specify content type as application/json will it go through since this object is in string format?

    Niranjan

    Reply
  39. jyotiranjan4 באפריל 2012 ב 14:39

    hey Pini..
    its really a gr8 code. A big thanks from my side.
    I am facing problem when am trying to get a JSON string like

    [{Key:{key:value,key:value,key:value,key:value},
    key: [{key:value,key:value,key:value,key:value}]}

    can you please help me out

    Reply
  40. Kawsar25 באפריל 2012 ב 11:36

    Thanks, I was looking for code like this

    Reply
  41. jj5 ביוני 2012 ב 17:16

    how about deserializing JSON object to List object?

    Reply
  42. bseebeck14 ביוני 2012 ב 21:16

    As may or may not have already been mentioned, for .NET 4.0, you can access the serializer mentioned in the article by "using System.Web.Script;" and then by instantiating a serializer with the following code:

    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

    Hope that helps.

    Reply
  43. Andamon A. Abilar13 ביולי 2012 ב 12:46

    Great… thank you so much for this…

    Reply
  44. Kobi29 ביולי 2012 ב 3:10

    How do I prevent JavaScriptSerializer from sorting my JSON fields alphabetically? Thanks.

    Reply