我有以下代码:
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; }
}
我发帖:
[{"Importancee":"adasdasd","Date":"2005-10-32","Descriptione":""},
{"Importance":"6.0","Date":"2015-10-02","Description":"a"}]
"重要性"是故意拼错的,以模拟丢失数据的情况。当我发布这篇文章时,我希望委托函数捕获无效数据,并让我知道所需的字段缺失。我还期望用于描述的正则表达式会导致1个字符描述"a"的错误。相反,Json.net的反序列化器跳过缺失的字段,并将这些属性设置为空,并将第二个Description属性设置为"a"字符串。它完全忽略了数据注释。有没有办法得到Json。. NET识别注释?
您可以从数据注释属性生成一个JSchema:
http://www.newtonsoft.com/jsonschema/help/html/GenerateWithDataAnnotations.htm并使用
验证它们http://www.newtonsoft.com/json/help/html/JsonSchema.htmData Annotations不会直接工作,但我相信您只需稍加努力就能得到所需的内容。