2015-02-10 59 views
0

我有以下設置:與JsonIgnore摘要屬性被序列化(Json.NET)

public abstract class A 
{ 
    [JsonIgnore] 
    public abstract Type Foo { get; } 
} 

public abstract class B : A 
{ 
    public override Type Foo { get { return typeof(D); } } 
} 

public class C : B 
{ 
} 

public abstract class D 
{ 
} 

我的問題是,當我通過以下序列C的實例:

JsonConvert.SerializeObject(instanceOfC, serializationSettings)); 

生成的JSON包含屬性Foo的條目。這是預期的結果嗎?

serializationSettings如下:

JsonSerializerSettings _serializationSettings = new JsonSerializerSettings 
{ 
    PreserveReferencesHandling = PreserveReferencesHandling.Objects, 
    ReferenceLoopHandling = ReferenceLoopHandling.Serialize, 
    TypeNameHandling = TypeNameHandling.All, 
    ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor 
}; 

編輯:使用Json.NET 6.0.0和.NET 4.5。

+0

我不能和你給的代碼重現此問題。請參閱https://dotnetfiddle.net/aEUy3p – 2015-02-11 15:09:07

回答

0

我有同樣的問題,我已經通過指定這樣JsonSerializerSettings的「ContractResolver」屬性(初始化所有必要的屬性你)解決它:

var settings = new JsonSerializerSettings 
     { 
      Formatting = Formatting.None, 
      ContractResolver = new PublicNotInternalPropertiesCamelCaseContractResolver() 

     }; 

這裏是我的PublicNotInternalPropertiesCamelCaseContractResolver:

public class PublicNotInternalPropertiesCamelCaseContractResolver : CamelCasePropertyNamesContractResolver 
{ 
    #region Overrides of DefaultContractResolver 

    protected override List<MemberInfo> GetSerializableMembers(Type objectType) 
    { 
     var members = base 
      .GetSerializableMembers(objectType) 
      .Where(m => m.GetCustomAttribute<InternalAttribute>() == null) 
      .ToList(); 

     return members; 
    } 

    #endregion 
} 

我不得不創建屬性「InternalAttribute」,因爲該解決方案不符合JsonIgnoreAttribute出於某些原因工作:

public class InternalAttribute : Attribute 
{ 

} 

我用它是這樣的:

public abstract class RavenDbEntity 
{ 
    private string _dbKey; 

    [Internal] 
    public string DbKey 
    { 
     get { return _dbKey; } 
     set 
     { 
      _dbKey = value; 
      Id = int.Parse(value.Split('/')[1]); 
     } 
    } 

    public int Id { get; set; } 
} 

所以輸出JSON將不DBKEY財產