[英]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.