Bug with Required.Always

Jul 1, 2010 at 11:55 PM

I have some code that looks like this:

    [JsonProperty(Required=Required.Always)]
    Uri MyField;

If MyField is null, the serializer saves it without problems, but when I try to read it back (using the same settings), I get an exception "Required property 'MyField' expects a value but got null."

In other words, the serializer writes output that it cannot read.  I think a better design would be to throw an exception rather than saving invalid data.  Otherwise these errors aren't caught until much later when attempting to reload the data.

Also, the documentation for "Required.Always" could be clearer.  I interpreted it to mean that the field must appear in the JSON tree, not that the field cannot be null.  Arguably both would be useful behaviors.

Thanks!

Coordinator
Jul 3, 2010 at 8:39 AM
Edited Jul 3, 2010 at 10:18 AM

Done. Serializer now validates when writing JSON for that property.

I'm not sure what you mean about the documentation. I think the Required enum is pretty clear about what each value does.

 

namespace Newtonsoft.Json
{
  /// <summary>
  /// Indicating whether a property is required.
  /// </summary>
  public enum Required
  {
    /// <summary>
    /// The property is not required. The default state.
    /// </summary>
    Default,
    /// <summary>
    /// The property must be defined in JSON but can be a null value.
    /// </summary>
    AllowNull,
    /// <summary>
    /// The property must be defined in JSON and cannot be a null value.
    /// </summary>
    Always
  }
}