JSON.Net - 反序列化为具有继承的类

本文关键字:继承 Net 反序列化 JSON | 更新日期: 2023-09-27 18:31:45

有了 JSON.Net,如何让反序列化过程忽略从父类继承的字段(我无权访问)。

我的 JSON 提要中有一个字段,它与从系统类继承的名称相同。当它尝试反序列化时,它因此失败(带有确切的错误消息:

A member with the name 'Location' already exists on 'Client.JSON.MyClass'. Use the JsonPropertyAttribute to specify another name.

位置是在父类中定义的,父类也是一个系统类,因此我无权访问该类以定义 JsonIgnore 属性。

如何绕过此功能,以便无需尝试将 JSON 位置属性反序列化为 MyClass 继承的系统类即可进行反序列化?

最后要注意的是,JSON 源是使用 WCF 数据服务生成的,因此包含"d"根数组 - 我被告知有关 ContractResolver 的信息,但由于"d"数组(使用以下代码),我无法使其工作:

using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
namespace Client.JSON
{
    public class MyClassContractResolver : DefaultContractResolver
    {
        protected override IList<JsonProperty> CreateProperties(JsonObjectContract t)
        {
            IList<JsonProperty> properties = base.CreateProperties(t);
            properties =
                properties.Where(p => p.PropertyName.StartsWith('J'.ToString())).ToList();
            return properties;
        }
    }
}

并使用以下代码反序列化:

jsonAppointments = JsonConvert.DeserializeObject<RootMyClass>(myJsonString, new JsonSerializerSettings { ContractResolver = new MyClassContractResolver() });

如果有人知道如何做到这一点,将不胜感激!谢谢。顺便说一下,这是使用紧凑框架。

JSON.Net - 反序列化为具有继承的类

我面临着类似的问题。我通过隐藏 base 属性解决了它,但没有更改其行为。

假设Location属于 string 类型:

class MyClass : RootMyClass
{
    [JsonIgnore] public new string Location
    {
        get
        {
            return base.Location;
        }
        set
        {
            base.Location = value;
        }
    }
}