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

How to Ignoring Fields and Properties Conditionally During Serialization Using JSON.Net?(如何在使用 JSON.Net 进行序列化期间有条件地忽略字段和属性?)

本文介绍了如何在使用 JSON.Net 进行序列化期间有条件地忽略字段和属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to Ignoring Fields and Properties Conditionally During Serialization Using JSON.Net? I can't inherit from JsonIgnoreAttribute because it's a sealed class. What should I do?

推荐答案

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

I found the answer. I inherit from JsonConverter and create a new convertor.

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);
    }
}

这篇关于如何在使用 JSON.Net 进行序列化期间有条件地忽略字段和属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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