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

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

问题描述

我正在使用 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 时,我才想将 JsonIgnore() 属性添加到 Test2List 属性.如果它不为空,那么我想将它包含在我的 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,则有一个 NullValueHandling 属性,您可以将其设置为忽略.

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 忽略类中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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