Maxime Rossini
Maxime Rossini

Reputation: 3879

Serializing with Json.NET: how to require a property not being null?

Using Newtonsoft's Json.NET serializer, is it possible to require a property to contain a non-null value and throw an exception on serialization if this not the case? Something like:

public class Foo
{
    [JsonProperty("bar", SerializationRequired = SerializationRequired.DisallowNull)]
    public string Bar { get; set; }
}

I know it is possible to do this upon deserialization (using the Required property of JsonProperty), but I cannot find anything on this for serialization.

Upvotes: 4

Views: 9022

Answers (2)

Brian
Brian

Reputation: 25834

This is now possible by setting the JsonPropertyAttribute to Required.Always.

This requires Newtonsoft 12.0.1+, which didn't exist at the time this question was asked.

The example below throws a JsonSerializationException ( "Required property 'Value' expects a value but got null. Path '', line 1, position 16." ):

void Main()
{
    string json = @"{'Value': null }";
    Demo res = JsonConvert.DeserializeObject<Demo>(json);
}

class Demo
{
    [JsonProperty(Required = Required.Always)]
    public string Value { get; set;}
}

Upvotes: 2

pijemcolu
pijemcolu

Reputation: 2605

Following Newtonsoft serialization error handling documentation you could handle the null atribute within an OnError() method. I am not entirely sure what would you pass to the SerializeObject() as a NullValueHandling parameter.

public class Foo
{
     [JsonProperty]
     public string Bar 
     {
         get 
         {
             if(Bar == null)
             {
                 throw new Exception("Bar is null");
             }
             return Bar;
         }
         set { Bar = value;}

     [OnError]
     internal void OnError(StreamingContext context, ErrorContext errorContext)
     {
          // specify that the error has been handled
          errorContext.Handled = true;
          // handle here, throw an exception or ...
     }
}


int main()
{
     JsonConvert.SerializeObject(new Foo(), 
                        Newtonsoft.Json.Formatting.None, 
                        new JsonSerializerSettings { 
                            NullValueHandling = NullValueHandling.Ignore
                        });
}

Upvotes: 0

Related Questions