0

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

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

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

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

如何绕过此问题,以便可以在不尝试将 JSON Location 属性反序列化到 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() });

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

4

1 回答 1

0

我面临着类似的问题。我通过隐藏基本属性来解决它,但没有改变它的行为。

假设它Location是类型string

class MyClass : RootMyClass
{
    [JsonIgnore] public new string Location
    {
        get
        {
            return base.Location;
        }
        set
        {
            base.Location = value;
        }
    }
}
于 2014-05-08T10:14:55.120 回答