Blog Archives

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/

C# .Net Clone and Copy Objects using Extension Methods

One of my earliest blog articles – Clone Objects in .Net Using Reflections – briefly discusses shallow and deep object copying and cloning.

For more info. on the semantics and what these terms really mean, see referenced wikipedia article.

You may or may not already be familiar with cloning native objects in .Net, such as the datatable. However, for custom classes, you are left to your own creations.

With the advent of extension methods in .Net, the functionality to copy objects can now be moved from static helper classes to inheritable extension methods and has new life and renewed usability. See code snippet below.

Thanks goes to R. Prestol for this one.

public static T GetCopy<T>(this T S)
    {
        T newObj = Activator.CreateInstance<T>();

        foreach (PropertyInfo i in newObj.GetType().GetProperties())
        {

//"EntitySet" is specific to link and this conditional logic is optional/can be ignored
            if (i.CanWrite && i.PropertyType.Name.Contains("EntitySet") == false)
            {
                object value = S.GetType().GetProperty(i.Name).GetValue(S, null);
                i.SetValue(newObj, value, null);           
            }
        }

        return newObj;
}

References
MSDN (Extension Methods), http://msdn.microsoft.com/en-us/library/bb383977.aspx
“Clone Objects in .Net Using Reflections”, http://ronniediaz.com/2010/03/02/clone-objects-in-net-using-reflections/
Wikipedia, “Object Copy”, http://en.wikipedia.org/wiki/Object_copy

Bind Control to an Object in Windows Forms

Simple solution for basic binding in Windows Forms app. This would NOT be recommended if you are using ASP .Net, Silverlight, WCF, RIA or any other services to retrieve the data as these project types have much better support for binding to controls.

C#:

static class dataaccess {
static mytype object;
}

//on app load
object = new mytype();

//on form load
tbField1.DataBindings.Add("Text", dataaccess.object.property, "Field1")
Follow

Get every new post delivered to your Inbox.