想要序列化Json有时会包含[JsonIgnore]

时间:2013-06-11 19:11:07

标签: c# asp.net-mvc json serialization json.net

我有95%的类不希望序列化一些否定属性。所以我使用[JsonIgnore]属性& Newtonsoft.Json,它工作正常。

但是,我只有很少的方法想要返回包含[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")
        };
    }

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

您可以使用IContractResolver

public class IncludeIgnored : DefaultContractResolver
{
    private readonly bool _includeIgnored;

    public IncludeIgnored(bool includeIgnored)
    {
        _includeIgnored = includeIgnored;
    }

    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

        foreach (var item in properties)
        {
            item.Ignored = !_includeIgnored;
        }

        return properties;
    }
}

然后当你打电话给你的序列化器

var serializedObject= JsonConvert.SerializeObject(myObject, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new IncludeIgnored(true) });