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.

3
  • A default string is null. NullValueHandling = NullValueHandling.Ignore newtonsoft.com/json/help/html/… Commented May 26, 2016 at 12:00
  • @DavidPine An empty string, or a whitespace string are not the same as a null string... Commented May 26, 2016 at 12:01
  • @RB. I know, I was trying to share how to do it for null. Still looking for whitespace handling. Commented May 26, 2016 at 12:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.