在DefaultContractResolver中重载方法来反序列化私有setter



我有一个具有私有设置的properties类,我希望使用Json.Net对这些属性进行反序列化。我知道我可以使用[JsonProperty]属性来做到这一点,我想通过实现DefaultContractResolver来做到这一点。这里是一些示例代码,我一直在使用,但这不起作用。

static void Main(string[] args)
{
    var a = new a();
    a.s = "somestring";
    a.set();
    Console.WriteLine(JsonConvert.SerializeObject(a));
    var strrr = JsonConvert.SerializeObject(a);
    var strobj = JsonConvert.DeserializeObject<a>(strrr,new                        JsonSerializerSettings
    {
        ContractResolver = new PrivateSetterContractResolver()
    });
    Console.Read();
}

这是我要序列化的类

public class a
{
    private int test;
    public int Test
    {
        get { return test; }
        private set { test = value; }
    }
    public string s { get; set; }
    public void set()
    {
        test = 33;
    }
}

这是DefaultContractResolver

的实现
public class PrivateSetterContractResolver : DefaultContractResolver
{
    protected override List<MemberInfo> GetSerializableMembers(Type objectType)
    {
        // whait do i do here ??? 
        //this dosent work
        return new List<MemberInfo>(objectType.GetProperties().ToList());
    }
}

在这里找到了解决方案. 我试图推翻错误的方法。您需要重写CreateProperty方法

protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var prop = base.CreateProperty(member, memberSerialization);
        if (!prop.Writable)
        {
            var property = member as PropertyInfo;
            if (property != null)
            {
                var hasPrivateSetter = property.GetSetMethod(true) != null;
                prop.Writable = hasPrivateSetter;
            }
        }
        return prop;
    }

JsonPropertyAttribute标记私有属性或带有私有setter的属性就足够了。然后它们也被自动序列化。所以不需要重写。

所以class看起来像:

public class a
{
    private int test;
    [JsonProperty]
    public int Test
    {
        get { return test; }
        private set { test = value; }
    }
    public string s { get; set; }
    [JsonProperty]
    public string anotherProperty { get; private set;}        
    public void set()
    {
        test = 33;
    }
}

如解决方案/答案所述:Json中的私有setter。净

我为此编写了一个源代码发行版NuGet,它安装了一个带有两个自定义契约解析器的文件:

  • PrivateSetterContractResolver
  • PrivateSetterCamelCasePropertyNamesContractResolver

安装NuGet:

Install-Package JsonNet.PrivateSettersContractResolvers.Source

然后使用任意的解析器:

var settings = new JsonSerializerSettings
{
    ContractResolver = new PrivateSetterContractResolver()
};
var model = JsonConvert.DeserializeObject<Model>(json, settings);

你可以在这里阅读:http://danielwertheim.se/json-net-private-setters-nuget/

GitHub repo: https://github.com/danielwertheim/jsonnet-privatesetterscontractresolvers

相关内容

  • 没有找到相关文章

最新更新