如何在运行时忽略某些 DataMember JSON

How to Ignore Some DataMember on Runtime JSON

//我希望一些数据成员根据某些条件不全部序列化。

class Days
{
}

class Weeks
{
}

class Months 

{
List<Days> listDays=new List<Days>();
List<Months > listMonths=new List<Months >();
}

class Year
{
Months m=new Months();
  if(day=="monday")
{
listDays.add(day)
}

}

class Year
{
Months m=new Months();
  if(day=="monday")
{
listDays.add(day)
}


  i dont want to empty here months that i not used so i want to remove when json created     

{ "listMonths": [],"listDays": [ "Monday"]}

"listMonths": [] 给我一些解决方案,这样我就可以在序列化时忽略不必要的数据成员。

你可以试试SerializeObject的重载方法排除空对象。类似下面

JsonConvert.SerializeObject(jSONDocument, 
                        Newtonsoft.Json.Formatting.None, 
                        new JsonSerializerSettings { 
                            NullValueHandling = NullValueHandling.Ignore
                        });

不幸的是,没有序列化程序选项可以忽略空集合。但是,您可以使用 DefaultContractResolver 忽略空集合

public class EmptyCollectionContractResolver : DefaultContractResolver
{
    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        JsonProperty property = base.CreateProperty(member, memberSerialization);

        Predicate<object> shouldSerialize = property.ShouldSerialize;
        property.ShouldSerialize = obj => (shouldSerialize == null || shouldSerialize(obj)) && !IsEmptyCollection(property, obj);
        return property;
    }

    private bool IsEmptyCollection(JsonProperty property, object target)
    {
        var value = property.ValueProvider.GetValue(target);
        var collection = value as ICollection;
        if (collection != null && collection.Count == 0)
            return true;

        if (!typeof(IEnumerable).IsAssignableFrom(property.PropertyType))
            return false;

        var countProp = property.PropertyType.GetProperty("Count");
        if (countProp == null)
            return false;

        var count = (int)countProp.GetValue(value, null);
        return count == 0;
    }
}

并将SerializeObject改为

json = JsonConvert.SerializeObject(jSONDocument,
                    Newtonsoft.Json.Formatting.None,
                    new JsonSerializerSettings
                    {
                        ContractResolver = new EmptyCollectionContractResolver(),
                        NullValueHandling = NullValueHandling.Ignore
                    });