Tagged: Web Service

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 🙂

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


Using JSON – Some observations

When using JSON with Web Services (classic web service or WCF service), you might get an error “JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.” when your json string is too big. If you are using JavaScriptSerializer class to serilaize your object, then there is a property ser.MaxJsonLength that you can set to allow for more size. But somehow, I still got the error, and I had to make that setting in web.config file. If you are using DataContractJsonSerializer class (using System.Runtime.Serialization.Json namespace), then you don’t have MaxJsonLength property for that class, but adding configuration settings in web.config works like a charm.

Here is how you change MaxJsonLength using web.config:

        <jsonSerialization maxJsonLength=”2147483647″></jsonSerialization>