小编Jam*_*mie的帖子

Newtonsoft.Json CustomContractResolver 排除空对象节点

我正在尝试序列化一组包含各种类型的对象,包括对其他自定义类型的对象引用。我希望当属性成员均为默认值或 null 时排除这些对象引用。这是设置:

public class ObjectA
{
    [DefaultValue(2)]
    [JsonProperty(PropertyName = "propertyA")]
    public int PropertyA { get; set; } = 6;

    [JsonProperty(PropertyName = "objectB")]
    public ObjectB ObjectB { get; set; } = new ObjectB();
}

public class ObjectB
{
    [DefaultValue(2)]
    [JsonProperty(PropertyName = "propertyA")]
    public int PropertyA { get; set; } = 2;

    [JsonProperty(PropertyName = "propertyB")]
    public string PropertyB { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

问题是当我使用以下命令序列化 ObjectA 时:

var settings = new JsonSerializerSettings();

settings.NullValueHandling = NullValueHandling.Ignore;
settings.DefaultValueHandling = DefaultValueHandling.Ignore;

return JsonConvert.SerializeObject(ObjectA, settings);
Run Code Online (Sandbox Code Playgroud)

我想看看这个: …

c# parsing json json.net

6
推荐指数
1
解决办法
5848
查看次数

标签 统计

c# ×1

json ×1

json.net ×1

parsing ×1