DCSIMG
Convert objects to JSON in C# using JavaScriptSerializer - Pini Dayan

Pini Dayan

The best thing about a boolean is even if you are wrong, you are only off by a bit.

Convert objects to JSON in C# using JavaScriptSerializer

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. 

Comments

kris said:

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?

# June 3, 2009 10:02 PM

Pini Dayan said:

Well good question

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

# June 9, 2009 3:18 PM

sunil said:

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

# October 15, 2009 5:08 AM

Pini Dayan said:

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

# October 19, 2009 7:20 AM

Itamar Gigi said:

Hello pini you are great and wonderfull man.

excellent code.

you very helped me with this solution.

# January 1, 2010 9:26 PM

Pini Dayan said:

You welocme.

Thanks

# January 5, 2010 9:57 AM

Bill Sternberger said:

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

# February 26, 2010 3:56 PM

Pini Dayan said:

You welcome :-)

# February 28, 2010 10:20 AM

Conan said:

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!

# March 11, 2010 11:54 AM

aQuila said:

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

# March 25, 2010 5:52 PM

aQuila said:

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

# March 26, 2010 10:12 AM

Pini Dayan said:

LOL, Thanks man

Come again :-)

# March 28, 2010 11:52 AM

Pini Dayan said:

LOL, Thanks man

Come again :-)

# March 28, 2010 11:52 AM

Pini Dayan said:

Simply use the Desialize method :-)

If you have any question write to my mail i could then answer faster

Pinid@sela.co.il

# March 28, 2010 11:58 AM

Jason said:

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.

# May 16, 2010 6:50 AM

satya said:

Thnks to give the Serialization code...

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

# August 17, 2010 4:29 PM

Vince said:

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!

# September 11, 2010 1:22 AM

Akhilesh said:

Hi,

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

Thanks

# September 15, 2010 2:43 PM

Shane van Wyk said:

Now how do you convert it back to the object?

# September 16, 2010 12:08 PM

binhvu said:

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<Employee> oList = new List<Employee>() { oEmployee1, oEmployee2, oEmployee3 };

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

           string sJSON = oSerializer.Serialize(oList);

           List<Employee> newList = oSerializer.Deserialize<List<Employee>>(sJSON);

           string nJson = oSerializer.Serialize(newList);

           MessageBox.Show(nJson);

# October 19, 2010 6:53 AM

ganesh said:

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

# October 25, 2010 11:04 AM

Ryan Sameie said:

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?

# November 27, 2010 3:57 PM

Dan Anos said:

Is it possible to use this with anonymous types?

# November 30, 2010 7:15 PM

Thien Le said:

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

# March 8, 2011 9:12 AM

Hsan said:

how to Dynamic data ?

# March 15, 2011 12:42 AM

manju said:

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

www.dotnetspider.com/.../282367-Json-console.aspx

# March 24, 2011 1:36 PM

Zaguerinho said:

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

Regards

jorge.

# April 23, 2011 9:58 AM

ايفون said:

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

# May 10, 2011 4:53 PM

ايفون said:

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

# May 10, 2011 4:54 PM

Newton said:

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     <script src="../../Scripts/ConvertCobjectToJavaObject.js" type="text/javascript"></script>

step 5 add this script block to your web page

   <script type="text/javascript">

       var convertedObject = {};

       $(function () {

           convertedObject = convertToJavaObject('<%=Model.PropertiesAsString%>');

       });

   </script>

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

# July 11, 2011 3:39 AM

Yavuz Yasin CELIK said:

/* 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> arr1 = new List<Arr1>();

           List<Arr2> arr2 = new List<Arr2>();

           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<Arr2> 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

# August 11, 2011 2:51 PM

Don said:

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!

# September 29, 2011 12:57 AM

Akhtar said:

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

# October 4, 2011 12:57 PM

test said:

anyone can do this

# November 11, 2011 2:44 PM

Serialize C# object to JSON JavaScriptSerializer .Net « Fraction of the Blogosphere said:

Pingback from  Serialize C# object to JSON JavaScriptSerializer .Net &laquo; Fraction of the Blogosphere

# November 29, 2011 6:25 PM

Serialize C# object to JSON JavaScriptSerializer .Net « Fraction of the Blogosphere said:

Pingback from  Serialize C# object to JSON JavaScriptSerializer .Net &laquo; Fraction of the Blogosphere

# November 29, 2011 6:27 PM

fh4 said:

I will try it, thanks.

There is thie library too: http://json.codeplex.com/

# January 4, 2012 11:57 AM

PepLamb said:

Awesome example!!!

( also supported in .NET 4 and above (4.5) )

A Question is this library available for Silverlight too?

# January 10, 2012 8:00 PM

Varun said:

How to parse this

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

# February 17, 2012 2:38 PM

Niranjan Raju said:

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

# February 24, 2012 7:29 AM

jyotiranjan said:

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

# April 4, 2012 2:39 PM

Kawsar said:

Thanks,  I was looking for code like this

# April 25, 2012 11:36 AM

Syam said:

# May 22, 2012 10:38 AM

Circular reference detected while serializing an object – C#, Json | PHP Developer Resource said:

Pingback from  Circular reference detected while serializing an object &#8211; C#, Json | PHP Developer Resource

# May 23, 2012 5:34 PM

jj said:

how about deserializing JSON object to List<xyz> object?

# June 5, 2012 5:16 PM

bseebeck said:

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.

# June 14, 2012 9:16 PM

Andamon A. Abilar said:

Great... thank you so much for this...

# July 13, 2012 12:46 PM

Kobi said:

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

# July 29, 2012 3:10 AM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: