gpt4 book ai didi

c# - NewtonSoft JSON.NET 的升级不会隐式序列化 protected 成员

转载 作者:太空狗 更新时间:2023-10-30 00:46:31 24 4
gpt4 key购买 nike

我刚刚将我的 NewtonSoft JSON.NET 版本从 3.0.0 版更新到 3.5.0 版,我注意到 protected 成员没有隐式序列化。

我有以下类(class):

public class SimpleFileContainer : IDto
{
public virtual string Name { get; protected set; }

public virtual string Path { get; protected set; }

public SimpleFileContainer(string name, string path)
{
Name = name;
Path = path;
}
}

下面的测试代码没有通过

var json = JsonConvert.SerializeObject(new SimpleFileContainer("Name", "Path"));

var deserialised = JsonConvert.DeserializeObject<SimpleFileContainer >(json);

Assert.That(deserialised.Name, Is.EqualTo("Name");

Name 和 Path 属性都为 null,除非我将属性集设为公开或使用以下属性添加更新类:

[JsonObject(MemberSerialization.OptOut)]
public class SimpleFileContainer : IDto
{
[JsonProperty]
public virtual string Name { get; protected set; }

[JsonProperty]
public virtual string Path { get; protected set; }

public SimpleFileContainer(string name, string path)
{
Name = name;
Path = path;
}
}

这是一个经常使用序列化过程的合理规模的项目,我不想通过代码将这些属性添加到每个类和成员。

有办法解决这个问题吗?

最佳答案

我今天遇到了同样的问题。幸运的是 Ayende 解决了这个问题,我正在与您分享。配置序列化程序时,更改 ContractResolver 上的 DefaultMembersSearchFlags 属性:

var serializer = new JsonSerializer
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
ContractResolver = new DefaultContractResolver
{
DefaultMembersSearchFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
},
TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple,

ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
};

关于c# - NewtonSoft JSON.NET 的升级不会隐式序列化 protected 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3092294/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com