如何在使用JSON.Net进行序列化期间有条件地忽略字段和属性?

时间:2015-12-16 05:42:52

标签: c# json.net

如何在使用JSON.Net进行序列化期间有条件地忽略字段和属性? 我无法继承JsonIgnoreAttribute,因为它是sealed类。我该怎么办?

2 个答案:

答案 0 :(得分:15)

您可以使用JSON.NET的 ShouldSerialize -syntax。在JSON.NET网站上有一个很好的例子:

http://www.newtonsoft.com/json/help/html/ConditionalProperties.htm

public class Employee
{
    public string Name { get; set; }
    public Employee Manager { get; set; }

    public bool ShouldSerializeManager()
    {
        // don't serialize the Manager property if an employee is their own manager
        return (Manager != this);
    }
}

如果ShouldSerialize不符合您的需求,您可以使用ContractResolvers完全控制序列化:http://www.newtonsoft.com/json/help/html/ContractResolver.htm

答案 1 :(得分:2)

我找到了答案。我继承自JsonConverter并创建一个新的转换器。

public class CustomJsonConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var list = (IList)value;

        JArray s = new JArray();

        foreach (var item in list)
        {
            JToken token = JToken.FromObject(item);
            JObject obj = new JObject();

            foreach (JProperty prop in token)
            {
                if (prop.Name != "Title") // your logic here
                    obj.Add(prop);
            }

            s.Add(obj);
        }

        s.WriteTo(writer);

    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
    }

    public override bool CanRead
    {
        get { return false; }
    }

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