在 json.net 中使用非公共设置器反序列化公共属性 [英] Deserializing public property with non-public setter in json.net

查看:18
本文介绍了在 json.net 中使用非公共设置器反序列化公共属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下课程 -

public class A 
{        
   public int P1 { get; internal set; }
}

使用 json.net,我可以使用 P1 属性序列化类型.但是,在反序列化期间,不设置 P1.在不修改 A 类的情况下,是否有一种内置方式来处理这个问题?就我而言,我正在使用来自不同程序集的类并且无法修改它.

Using json.net, I am able to serialize the type with P1 property. However, during deserialization, P1 is not set. Without modifying class A, is there an in build way to handle this? In my case, I am using a class from a different assembly and cannot modify it.

推荐答案

是的,您可以使用自定义 ContractResolver 使内部属性可写入 Json.Net.这是您需要的代码:

Yes, you can use a custom ContractResolver to make the internal property writable to Json.Net. Here is the code you would need:

class CustomResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty prop = base.CreateProperty(member, memberSerialization);

        if (member.DeclaringType == typeof(A) && prop.PropertyName == "P1")
        {
            prop.Writable = true;
        }

        return prop;
    }
}

要使用解析器,请创建 JsonSerializerSettings 的实例并将其 ContractResolver 属性设置为自定义解析器的新实例.然后,将设置传递给 JsonConvert.DeserializeObject().

To use the resolver, create an instance of JsonSerializerSettings and set its ContractResolver property to a new instance of the custom resolver. Then, pass the settings to JsonConvert.DeserializeObject<T>().

演示:

class Program
{
    static void Main(string[] args)
    {
        string json = @"{ ""P1"" : ""42"" }";

        JsonSerializerSettings settings = new JsonSerializerSettings();
        settings.ContractResolver = new CustomResolver();

        A a = JsonConvert.DeserializeObject<A>(json, settings);

        Console.WriteLine(a.P1);
    }
}

输出:

42

小提琴:https://dotnetfiddle.net/1fw2lC

这篇关于在 json.net 中使用非公共设置器反序列化公共属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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