2013-06-11 48 views
1

我有95%的類不想序列化一些否定屬性。所以我使用[JsonIgnore]屬性& Newtonsoft.Json,它工作正常。想要序列化Json包括[JsonIgnore]有時

但是,我只有幾個方法想要返回包含來自[JsonIgnore]的屬性的JSON。我該怎麼做?

謝謝大家

public class SubCatalog 
{ 
    [Key] 
    public int Id { get; set; } 

    [ForeignKey("Catalog")] 
    public int CatalogId { get; set; } 
    public string Name { get; set; } 

    [JsonIgnore] 
    public virtual Catalog Catalog { get; set; } 
    [JsonIgnore] 
    public virtual IList<Item> Items { get; set; } 
} 

使用這種方法,我想包括在實體的所有屬性。

public HttpResponseMessage GetSubCatalogs(int id) 
    { 
     var list = _uow.SubCatalogs.GetByCatalogId(id); 
     var json = JsonConvert.SerializeObject(list, 
               Formatting.Indented, 
               new JsonSerializerSettings 
               { 
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore 
               }); 

     return new HttpResponseMessage() 
     { 
      Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json") 
     }; 
    } 

回答

0

您可以嘗試實現自定義JsonConverter。

重寫WriteJson方法並在那裏實現自定義序列化。

public class Converter : JsonConverter 
{ 
    public override bool CanRead { get { return false; } } 
    public override bool CanWrite { get { return true; } } 


    public override bool CanConvert(Type objectType) 
    { 
     return objectType == typeof(SubCatalog); 
    } 

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) 
    { 
     throw new NotImplementedException(); 
    } 

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) 
    { 
      //serialization code here 
    } 
} 

該轉換器的加入實例序列化Converters財產或JsonSettings

相關問題