118

I am getting the k_BackingField in my returned json after serializing a xml file to a .net c# object.

I've added the DataContract and the DataMember attribute to the .net c# object but then I get nothing on the json, client end.

[XmlRoot("person")]
[Serializable]
public class LinkedIn
{
    [XmlElement("id")]
    public string ID { get; set; }

    [XmlElement("industry")]
    public string Industry { get; set; }

    [XmlElement("first-name")]
    public string FirstName { get; set; }

    [XmlElement("last-name")]
    public string LastName { get; set; }
    [XmlElement("headline")]
}

Example of the returned json:

home: Object
<FirstName>k__BackingField: "Storefront"
<LastName>k__BackingField: "Doors"
TZHX
  • 5,291
  • 15
  • 47
  • 56

13 Answers13

116

Remove [Serializable] from your class

JSK NS
  • 3,346
  • 2
  • 25
  • 42
Safaa Elgendi
  • 1,199
  • 2
  • 7
  • 3
  • 3
    Now I am wondering why I thought I needed [Serializable] in the first place. My Xml serialization works without and JSON works without it. – Rhyous Mar 03 '15 at 22:19
  • 14
    This doesn't work with WCF Services. When returning a payload using RESTful services this doesn't yield any data if you remove [Serializable]. Add System.Runtime.Serialization and use [DataContract] for class, [DataMember] for properties. – Ian Newland Aug 13 '15 at 01:03
  • This answer AND Ian comment seems to cover both cases. To WCF or not to WCF, that is the question. – granadaCoder Sep 16 '15 at 15:21
  • 1
    @Rhyous - in Web API you don't need [Serializable], because Web API is set up with the assumption you're going to be serializing and returning your objects (since that's basically the entire idea) - in other C# applications you generally need Serializable to differentiate serializable objects – Jon Story Feb 16 '16 at 16:17
  • Thank you, I was stuck with `[Serializable]`, so adding backing fields helped. – ohmusama Sep 08 '17 at 20:09
  • 1
    Hello, It works but i need to keep [Serializable] to my class because i have used same class for my backoffice and i have used SQL server session . to store this class in session i need to keep [Serializable]. any other solution please ? – Abhijit Pandya Jul 30 '18 at 14:18
  • @IanNewland You are right. On removing [Serializable], the WCF service doesn't yield any data. I did add [DataContract] for Class and [DataMember] for properties - but I still see no Data. Can you suggest – Prem Sep 29 '21 at 16:45
66

The default WebApi serializer will add that "__BackingField:" syntax to c# auto-properties. Add this to your WebConfig in App_Start to get the cleaner looking json that you might be looking for.

using Newtonsoft.Json;
...

config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings();
CodyBugstein
  • 21,984
  • 61
  • 207
  • 363
Dan
  • 1,011
  • 9
  • 6
47

Automatic Property syntax is actually not recommended if the class can be used in serialization. Reason being the backing field is generated by compiler which can be different each time code is compiled. This can cause incompatibility issues even if no change is made to the class (just recompiling the code).

I think applying DataMember attribute will fix the issue in this case. But I would recommend to use full property syntax, if the class needs to be used in serialization.

jags
  • 2,022
  • 26
  • 34
39

We have some objects which are marked as [Serializable] so they can be serialised using traditional methods, but which we need to have cleanly serialised in JSON for use with Web API. Setting IgnoreSerializableAttribute to true will stop Newtonsoft.Json from behaving like Microsoft's serialisers and instead it will just serialise the public properties.

TLDR: Add this to WebApiConfig.cs:

((Newtonsoft.Json.Serialization.DefaultContractResolver)config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = true;

Moderator: Rather than deleting a really good answer to a question that has been asked several times, please delete the duplicate question. This is a valid answer to a valid question.

Richard
  • 4,740
  • 4
  • 32
  • 39
  • 4
    This should be the right answer. Removing Serialization or using datacontract and datamember attributes is not always the correct solution. – Houssam Hamdan Feb 24 '17 at 07:43
  • Many of us are not, including OP, using Webapi or MVVM or what ever it is you guys are on about. What is app_start and webapiconfig when I have a normal soap WCF service with service.svc? – Christian Dec 19 '19 at 10:40
  • Thanks , this solution works for me. Its remove k__BackingField from WEB API response. – Vijay Chauhan Nov 06 '20 at 06:26
13

Simple Easy and Decent way to expose data We need to expose out data in object to easy readable and consistent format


First remove [Serializable]

    [Serializable]

now add [DataContract] in class and [DataMember] for property like below example

[DataContract]
public class UserDiscretion : UserReport
{
    [DataMember]
    public String DiscretionCode { get; set; }
    public String DiscretionDescription { get; set; }
}

Hope this help
Thanks.

  • 1
    If using Web API, there's no need to add the DataContract and DataMember attributes at all - simply return the object and it will be serialised automatically. – Jon Story Feb 16 '16 at 16:16
  • If anyone starting development from scratch so it will be great to use Web API which will provide Object return type will not require any type of type casting to exposing to client. But for @AlumCloud.com question, if he is in the existing application so solution for his problem will be by First remove [Serializable] then add [DataContract] in class and [DataMember] for property like below as suggested – Nagendra Upwanshi Aug 08 '16 at 18:47
  • 1
    This adds a tremendous amount of "noise" to your classes and is essentially unnecessary (see all the other comments). If one feels the need to actually do this, however, I would recommend using something like PostSharp to add the code for you during compilation so that it doesn't clutter up your classes with all of those attributes. – camainc Aug 14 '18 at 21:30
8

Couple of options:

  1. Remove [Serializable] from model

  2. Add [DataContract] and [DataMember] to your model along with [Serializable]

  3. Add below line to App_Start/WebApiConfig.cs

config.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings();
Jérémie Bertrand
  • 3,025
  • 3
  • 44
  • 53
4

Another solution that may help in case of JSON.NET. It may be enough to mark class with [Newtonsoft.Json.JsonObject] attribute.

I was working with cs classes built from xsd and was adding some properties using partial classes. After json serialization these properties were marked with k_BackingField. JsonFormatter settings mentioned in other answers helped as well, but more simple was to mark partial class with [JsonObject] attribute.

sarh
  • 6,371
  • 4
  • 25
  • 29
2

I was using DataContractJsonSerializer with a class from another assembly that had the Serializable attribute. The output contained "k__BackingField". Removing the Serializable attribute (in the other assembly) fixed this. Not sure why.

Little Endian
  • 784
  • 8
  • 19
0

Assuming you see this issue inside of your MVC project, I've found that it's pretty simple to replace the use of @Html.JsonData. Here is a snippet of code that has worked for me in the past:

<input type="hidden" id="Model" value="@Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model))" />

Not as elegant, but simple in a pinch.

Ryan Roark
  • 61
  • 6
0

I had this issue when I have self reference properties in my class such as;

class Person {
 List<Person> Friends { get; set;}
}

And there was a result, the person was friend with himself. I just made sure there was no self referencing objects in my result set. Hope this helps.

Teoman shipahi
  • 47,454
  • 15
  • 134
  • 158
0

I had to use the [Serializable] attributes, so removing it was not an option.

XmlSerializer ignores [XmlAttribute] in WebApi

The above resolution solved it for me.

GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;
JanBorup
  • 5,337
  • 1
  • 29
  • 17
0

in my case this error was for the Newtonsoft.Json Version, the server looked for 6.0.0 version and I had the 11.0, so I had to install the version 6.0.0

-2

Friends, don't declare properties like this:

public String DiscretionCode { get; set; }
public String DiscretionDescription { get; set; }

But, create auxiliar vars, like old....

private String discretionCode;

public String DiscretionCode 
{ 
    get { return discretionCode;}
    set { discretionCode = value; }
}
Will
  • 24,082
  • 14
  • 97
  • 108
  • 1
    Why? Could you give a reson? – Lucenty Jul 31 '17 at 06:49
  • @Lucenty it gives a JSON like this.. [{ "discreationCode" : "x"}], when serializing. – Ammar Ameerdeen Sep 08 '17 at 07:28
  • But this is what I would expect - this is how JSON serializes data. And I think that the code with auxiliar vars will give the same result. – Lucenty Sep 09 '17 at 08:51
  • k_BackingField has been added to indicate an auto-property has been serialised. If you refactor the auto-property to a property and a backing field then the problem would go away. I think there's better solutions in this thread but this works. – timB33 May 01 '18 at 12:34