How to ignore a property in class if null, using

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

I have the class like this:

class Test1
    public string ID { get; set; }
    public string Label { get; set; }
    public string URL { get; set; }
    public List<Test2> Test2List { get; set; }

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.


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.

Here’s a sample:

JsonSerializer _jsonWriter = new JsonSerializer {
                                 NullValueHandling = NullValueHandling.Ignore

Alternatively, as suggested by @amit

                            new JsonSerializerSettings { 
                                NullValueHandling = NullValueHandling.Ignore