如何使用json.net忽略类中的属性(如果为null) [英] How to ignore a property in class if null, using json.net

查看:179
本文介绍了如何使用json.net忽略类中的属性(如果为null)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Json.NET 将类序列化为JSON.

I am using Json.NET to serialize a class to JSON.

我有这样的课程:

class Test1
{
    [JsonProperty("id")]
    public string ID { get; set; }
    [JsonProperty("label")]
    public string Label { get; set; }
    [JsonProperty("url")]
    public string URL { get; set; }
    [JsonProperty("item")]
    public List<Test2> Test2List { get; set; }
}

仅当Test2Listnull时,我想向Test2List属性添加JsonIgnore()属性.如果它不为null,那么我想将其包含在json中.

I want to add a JsonIgnore() attribute to Test2List property only when Test2List is null. If it is not null then I want to include it in my json.

推荐答案

按照James Newton King的说法:如果您自己创建序列化程序而不是使用JavaScriptConvert,则会有一个

As per James Newton King: If you create the serializer yourself rather than using JavaScriptConvert there is a NullValueHandling property which you can set to ignore.

这里是一个示例:

JsonSerializer _jsonWriter = new JsonSerializer {
                                 NullValueHandling = NullValueHandling.Ignore
                             };


或者,按照@amit的建议


Alternatively, as suggested by @amit

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

这篇关于如何使用json.net忽略类中的属性(如果为null)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆