Serialize C# object to JSON JavaScriptSerializer .Net

//declare data you want to send as an object type
public class MyType {
//may simply contain properties mapping to your database rows or be more complex objects
//use [Serializable] attributes to mark props or methods as non-serialized
}
public void Page_Load(object sender, EventArgs e) {
MyType o1 = new MyType {p1="",p2=""};


Response.Write(JSONSerialize(o1));

Response.Write("<br /><br />");

MyType o2 = new MyType {p1="",p2=""};
List<MyType> olist = new List<MyType> {o1, o2};

Response.Write(JSONSerialize(olist));
}

public string JSONSerialize(MyType o) {
System.Web.Script.Serialization.JavaScriptSerializer sz = 
         new System.Web.Script.Serialization.JavaScriptSerializer();
return sz.Serialize(o);
}

//additional signature to handle lists of object
public string JSONSerialize(List<MyType> o) {
System.Web.Script.Serialization.JavaScriptSerializer sz = 
         new System.Web.Script.Serialization.JavaScriptSerializer();
return sz.Serialize(o);
}

References
MS Blogs, http://blogs.microsoft.co.il/blogs/pini_dayan/archive/2009/03/12/convert-objects-to-json-in-c-using-javascriptserializer.aspx
JSON.org, http://www.json.org/js.html
C# Cross-Site Page Access, http://stackoverflow.com/questions/6290053/setting-access-control-allow-origin-in-asp-net-mvc-simplest-possible-method
PHP Cross-Site Page Access, http://rayfd.wordpress.com/2007/03/28/why-wont-eval-eval-my-json-or-json-object-object-literal/
JS Eval string to JSON Object, http://rayfd.wordpress.com/2007/03/28/why-wont-eval-eval-my-json-or-json-object-object-literal/

About these ads

About Ronnie Diaz

Ronnie Diaz is an enterprise software engineer responsible for front-end and back-end development for companies in many industries. Heavily involved in cloud development, online retail, e-commerce and electronic ordering, fulfillment and customer relational systems.

Posted on November 29, 2011, in Programming & Development and tagged , , , , , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: