snippetcsharpCritical
How to ignore a property in class if null, using json.net
Viewed 0 times
netpropertyhowclassignoreusingjsonnull
Problem
I am using Json.NET to serialize a class to JSON.
I have the class like this:
I want to add a
I have the class like this:
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 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.Solution
As per James Newton King: If you create the serializer yourself rather than using JavaScriptConvert there is a
Here's a sample:
Alternatively, as suggested by @amit
NullValueHandling property which you can set to ignore.Here's a sample:
JsonSerializer _jsonWriter = new JsonSerializer {
NullValueHandling = NullValueHandling.Ignore
};Alternatively, as suggested by @amit
JsonConvert.SerializeObject(myObject,
Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});Code Snippets
JsonSerializer _jsonWriter = new JsonSerializer {
NullValueHandling = NullValueHandling.Ignore
};JsonConvert.SerializeObject(myObject,
Newtonsoft.Json.Formatting.None,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});Context
Stack Overflow Q#6507889, score: 877
Revisions (0)
No revisions yet.