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

查看:70
本文介绍了在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<T>().

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天全站免登陆