2011-12-21 76 views
7

我正在使用JSON.net序列化我的EntityFramework對象。JSON.net JsonIgnoreAttribute不能使用「EntityKey」屬性

過去,我創建了一個將「JsonIgnore」屬性應用於屬性的類,然後將我的主EntityFramework類的「MetadataType」屬性設置爲新創建的類。

下面是一個例子:

將被施加到EF類的類:

public class Role_DoNotSerialize 
    { 
     [JsonIgnore] 
     public string Users { get; set; } 
    } 

局部類文件對於EF類:

[MetadataType(typeof(Role_DoNotSerialize))] 
    public partial class Role 
    { 
    } 

在上述例如,序列化「角色」對象時,「用戶」屬性不會被序列化。

我的問題是,同樣的技術失敗,當我在的EntityKey屬性添加像這樣的工作:

public class Role_DoNotSerialize 
    { 
     [JsonIgnore] 
     public string Users { get; set; } 

     [JsonIgnore] 
     public System.Data.EntityKey EntityKey { get; set; } 
    } 

使用這個類中,「的EntityKey」屬性仍然系列化。我究竟做錯了什麼?

+0

寫得不錯,工作好的代碼。那麼,應該工作的兩個最高位,也就是說。 – 2012-06-18 15:32:55

+0

使用您的問題找到了我的問題的答案!+1 – theMothaShip 2013-07-10 13:46:23

回答

4

您可以通過實現自己的ContractResolver做到這一點(與JSON.NET 4.5示例代碼,但也有可能與舊版本)

public class ExcludeEntityKeyContractResolver : DefaultContractResolver 
{ 
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) 
    { 
     IList<JsonProperty> properties = base.CreateProperties(type,memberSerialization); 
     return properties.Where(p => p.PropertyType != typeof (System.Data.EntityKey)).ToList(); 
    } 
} 

然後你可以設置此設置ContractResolver爲您JsonSerializerSettings對象

JsonSerializerSettings serializerSettings = new JsonSerializerSettings(); 
serializerSettings.ContractResolver = new ExcludeEntityKeyContractResolver(); 

請注意,您並不僅限於那一個lambda函數,而是您可以實現任何您想要的檢查。您甚至可以覆蓋每個屬性的Converter以執行自定義序列化。

2

我認爲最新版本的JSON.NET現在就兌現。這個示例在我們的MVC網站上工作,但是您可以使用該字符串,但是您需要。

public ActionResult ContentJsonFormatted(object obj, Formatting formatting = Formatting.Indented) 
{ 
    string result = JsonConvert.SerializeObject(obj, formatting); 
    return Content(result, "text/plain"); 
} 
相關問題