0

Recently I found an annoying different behavior between net35 and net40 NewtonSoft Json library. For net40, the serialized payload is good. But for net35, the serialized payload includes annoying value k__BackingField.

Here is a sample code to repro the issue:

// Notice that there is no serializable attribute
public class SamplePayload
{
    public Guid Id { get; set; }
}

static void Main(string[] args)
{
    var writeStream = new MemoryStream();
    var formatter = new JsonMediaTypeFormatter();
    formatter.WriteToStreamAsync(typeof(SamplePayload), new SamplePayload(), writeStream, null, null).Wait();
    Console.WriteLine(System.Text.Encoding.UTF8.GetString(writeStream.ToArray()));
}

If reference a net40/net45 Json library, the serialized payload is like "Id" which is expected. But with net35 library, the serialized payload includes "k__BackingField".

I'm wondering why there is such a behavior difference? Is it a defect in NewtonSoft Json library, or a by-design behavior? If it is latter, what's the best practice to avoid such issue?

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
Yingqin
  • 195
  • 6

1 Answers1

1

.NET 3.5 is very old and k__BackingField is there by design AFAIK. Getting rid of it is well-documented. You need to check the version and when it includes that field, apply the solution linked here.

Community
  • 1
  • 1
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175