1

I want to force the user not to send a property in JSON string if it is null, even if it is nullable.

Basically:

Data { "NullableVariable": "Nullable Value" }

Correct.

Data {  }

Correct.

Data { "NullableVariable": null }

Incorrect.

Is there a way to achieve this?

Pecheneg
  • 768
  • 3
  • 11
  • 27

1 Answers1

1

You can force an exception to be thrown if and only if a property is present with a null value by setting JsonPropertyAttribute.Required to Required.DisallowNull, which means

The property is not required but it cannot be a null value.

Thus your type would look like:

public class Data
{
    [JsonProperty(Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
    public string NullableVariable { get; set; }
}

Notes:

  • When Required.DisallowNull is set, attempting to deserialize the following into the Data type above will throw an exception:

    {"NullableVariable":null} 
    

    While the following will all deserialize successfully:

    {}
    {"NullableVariable":""}
    {"NullableVariable":"Nullable Value"}
    
  • In order to successfully serialize the type when NullableVariable is null, you need to set JsonProperty.NullValueHandling = NullValueHandling.Ignore. This is because Required.DisallowNull will cause an exception to be thrown during serialization when the nullable member is null; NullValueHandling.Ignore suppresses this (as well as the output of the null value).

  • Required.DisallowNull was added in Json.NET 8.0.1 so be sure you are using this version or later.

dbc
  • 104,963
  • 20
  • 228
  • 340
  • Thanks @dbc, I have an earlier version so I won't be able to implement the solution, however I marked as an answer as it is the solution. – Pecheneg Sep 28 '17 at 09:40