1

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.

Hélder Gonçalves
  • 3,822
  • 13
  • 38
  • 63
  • A default `string` is `null`. `NullValueHandling = NullValueHandling.Ignore` http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_NullValueHandling.htm – David Pine May 26 '16 at 12:00
  • @DavidPine An empty string, or a whitespace string are not the same as a `null` string... – RB. May 26 '16 at 12:01
  • @RB. I know, I was trying to share how to do it for `null`. Still looking for whitespace handling. – David Pine May 26 '16 at 12:04

1 Answers1

3

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.

Community
  • 1
  • 1
David Pine
  • 23,787
  • 10
  • 79
  • 107