如何在使用 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 进行序列化期间有条件地忽略字段和属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!