【问题标题】:Why there are different behaviors between net35 and net40 NewtonSoft Json library为什么 net35 和 net40 NewtonSoft Json 库之间有不同的行为
【发布时间】: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 库中的缺陷,还是设计行为?如果是后者,避免此类问题的最佳做法是什么?

【问题讨论】:

标签: c# json json.net


【解决方案1】:

.NET 3.5 已经很老了,k__BackingField 是设计的 AFAIK。摆脱它是well-documented。您需要检查版本,当它包含该字段时,应用此处链接的解决方案。

【讨论】:

    猜你喜欢
    • 2012-10-15
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多