Tip: C# Automatic Properties, k_BackingField and JSON


If you are using automatic properties to define your data objects and you are trying to serialize these objects to a JSON string using DataContractSerializer (WCF/3.5), make sure you mark your data classes with [DataContract] and [DataMember] attributes (even if you are not really using WCF), a simple [Serializable] attribute will not do. If you just use [Serializable], the emitted JSON string will have a prefix tag “k_backingField” and the string is all mumbo-jumbo!

So if you use automatic properties, your class should look like this :)

 
    [DataContract] 
    public class Employee
    {
        [DataMember(Name = "FirstName", Order = 1)]
        public string FirstName { get; set; }
        [DataMember(Name = "LastName", Order = 2)]
        public string LastName { get; set; }
    }	

Cheers!

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