Json.NET - convert EmptyOrWhiteSpace string property to null

Is it possible to use a [JsonProperty] attribute to convert any empty string or filled with white spaces to null?

Something like:

 public class Request
 {
     [JsonProperty(NullOrWhiteSpaceValueHandling)] 
     public string Description {get;set;}
 }

The same way as nulls are skipped when rendered. When this property is "empty" the value is not set.

Upvotes: 1

Views: 700

Answers (1)

David Pine
David Pine

Reputation: 24525

You will need to implement a custom JsonConverter and assign it to the TrimmingConverter property of the JsonProperty attribute. There was an example of writing a customer TrimmingConverter detailed here. Once you have something similar to this implemented you should be able to set both the NullValueHandling and ItemConverterType properties. This will ensure that the converter will trim the string, and if it's null or empty or whitespace - it will be ignored for serialization.

public class Request
{
    [
       JsonProperty(NullValueHandling = NullValueHandling.Ignore, 
                    ItemConverterType = typeof(TrimmingConverter))
    ] 
    public string Description { get; set; }
}

Here is the official documentation for the JsonProperty.

Upvotes: 3

Related Questions