升级NewtonSoft JSON.NET不会隐式序列化受保护的成员 [英] Upgrade of NewtonSoft JSON.NET not implicitly serialising protected members

查看:83
本文介绍了升级NewtonSoft JSON.NET不会隐式序列化受保护的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚将NewtonSoft JSON.NET的版本从3.0.0更新到了3.5.0,我注意到受保护的成员并未隐式序列化.

I have just updated my version of NewtonSoft JSON.NET from version 3.0.0 to 3.5.0 and I have noticed that protected members are not implicitly serialised.

我有以下课程:

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");

名称"和路径"属性均为空,除非我将该属性设置为公共或添加具有以下属性的更新类:

both the Name and Path properties are null unless I either make the property sets public or add update the class with the following attributes:

[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;
    }
}

这是一个大小合理的项目,它大量使用序列化过程,我不想遍历将这些属性添加到每个类和成员的代码.

This is a reasonably sized project that uses the serialization process a lot, I do not want to go through the code adding these attributes to every class and member.

有没有办法解决这个问题?

Is there a way round this?

推荐答案

我今天遇到了同样的问题.幸运的是Ayende有了修复程序,我正在与您分享.配置序列化程序时,请在ContractResolver上更改DefaultMembersSearchFlags属性:

I had this same problem today. Luckily Ayende had the fix and I am sharing it with you. When you configure the serializer, change the DefaultMembersSearchFlags property on the ContractResolver:

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

                            ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor
                        };

这篇关于升级NewtonSoft JSON.NET不会隐式序列化受保护的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆