[英]JSON.Net - Deserialize into a class which has Inheritance
使用JSON.Net,如何获取反序列化过程以忽略从父类(我无权访问)继承的字段。
我的JSON Feed中有一个字段,该字段与从系统类继承的名称相同。 并且当它尝试反序列化时,它会因此失败(带有确切的错误消息:
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。
我面临着类似的问题。 我通过隐藏基本属性来解决它,但未更改其行为。
假设Location
为string
类型:
class MyClass : RootMyClass
{
[JsonIgnore] public new string Location
{
get
{
return base.Location;
}
set
{
base.Location = value;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.