Jesse Adam
Jesse Adam

Reputation: 415

Json.NET does not recognize Data Annotations and allows the data through

I have the following code:

public class EventController : ApiController
{
    //public IHttpActionResult Post(List<Event> Events)
    public IHttpActionResult Post(Newtonsoft.Json.Linq.JArray J)
    {
        //Debug.WriteLine(J.ToString());

        List<Event> Events = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Event>>(J.ToString(), new Newtonsoft.Json.JsonSerializerSettings {
            Error = delegate(object sender, ErrorEventArgs args) {
            Debug.WriteLine(args.ErrorContext.Error.Message);
            args.ErrorContext.Handled = true;
         },
            Converters = { new IsoDateTimeConverter() }
         }
      );

      foreach (Event Event in Events)
      {
         Debug.WriteLine(Event.Importance.ToString());
         Debug.WriteLine(Event.Date.ToString());
         Debug.WriteLine(Event.Description);
      }
   }
}

public class Event
{
    [DataAnnotationsExtensions.Integer(ErrorMessage = "{0} must be a number.")]
    [Range(0,10),Required]        
    public Int32 Importance { get; set; }

    //[OnConversionError: "Please enter a valid date."]
    [Required]
    [DataAnnotationsExtensions.Date]
    public object Date { get; set; }

    [RegularExpression(@"^.{20,100}$", ErrorMessage="{0} must be between 20 and 100 characters.")]
    [Required]
    public string Description { get; set; }
}

I'm posting:

[{"Importancee":"adasdasd","Date":"2005-10-32","Descriptione":""},
{"Importance":"6.0","Date":"2015-10-02","Description":"a"}]

"Importance" is misspelled on purpose to simulate the scenario of missing data. When I post this I expect the delegate function to capture the invalid data and let me know the required fields are missing. I also expect the Regular Expression used for Description to cause an error for the 1 character description "a". Instead Json.net's Deserializer skips the missing fields and sets those properties to null and it sets the 2nd Description property to the "a" string. It's completely ignoring the Data Annotations. Is there any way to get Json.NET to recognize the Annotations?

Upvotes: 4

Views: 5789

Answers (1)

Troels Larsen
Troels Larsen

Reputation: 4631

You could generate a JSchema from the Data Annotation attributes:

http://www.newtonsoft.com/jsonschema/help/html/GenerateWithDataAnnotations.htm

And validate them them using:

http://www.newtonsoft.com/json/help/html/JsonSchema.htm

Data Annotations will not work directly, but with little effort, I believe you can get what you need.

Upvotes: 5

Related Questions