【发布时间】:2017-04-03 21:35:03
【问题描述】:
最近我发现 net35 和 net40 NewtonSoft Json 库之间存在令人讨厌的不同行为。对于 net40,序列化的有效载荷很好。但是对于 net35,序列化的有效载荷包含烦人的值 k__BackingField。
这是重现问题的示例代码:
// 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()));
}
如果引用 net40/net45 Json 库,则序列化的有效负载类似于预期的“Id”。但是对于 net35 库,序列化的有效载荷包括“k__BackingField”。
我想知道为什么会有这样的行为差异?它是 NewtonSoft Json 库中的缺陷,还是设计行为?如果是后者,避免此类问题的最佳做法是什么?
【问题讨论】: