Getting Rid of k__BackingField in Serialization

We have an application that uses WebApi to send out results for some queries. This has worked well and outputs nice JSON results courtesy of JSON.NET (thanks to James for that great library!).

Today I ran into a problem: the serialized JSON was corrupted with content that looks like this:

   1: {

   2:     "<Data>k__BackingField" : [{

   3:             "item1",

   4:             "item2"

   5:         }

   6:     ],

   7:     "<Totals>k__BackingField" : null,

   8:     "_count" : 2,

   9:     "_pageSize" : 10,

  10:     "_page" : 1,

  11:     "<Sort>k__BackingField" : "Date"

  12: }

My reaction was puzzlement: why on earth would a straightforward class with properies like Data and Count suddenly start spitting out weird JSON like this?

SO to the Rescue?

Obviously the first port of call was a search on StackOverflow

From this article we get some clues: the k__BackingField is created by automatic properties in C#, and that DataContractJsonSerializer does this.

But we’re not supposed to be using DataContractJsonSerializer, we’ve got WebApi which uses JSON.NET?


Turns out the cause is the SerializableAttribute – because I’d added that to the class, the object result from the WebAPI method got passed to DataContractJsonSerializer.

I had not seen this before because most of the results I had output didn’t have this attribute, even though the base class did. I removed this, and bingo, the results were fixed:

   1: {

   2:     "Data" : [{

   3:         "item1",

   4:         "item2"

   5:         }

   6:     ],

   7:     "Totals" : null,

   8:     "Count" : 2,

   9:     "PageSize" : 10,

  10:     "Page" : 1,

  11:     "Sort" : "Date"

  12: }


Leave a Reply

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

You are commenting using your 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