在调用DeserializeObject< Object>(...)时验证Json数据 [英] Validate Json data while calling DeserializeObject<Object>( ... )

查看:62
本文介绍了在调用DeserializeObject< Object>(...)时验证Json数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

反序列化后,我想验证Json代码.
例如,如果我有...

I want to validate Json code after I deserialize it.
For example if I have ...

using Newtonsoft.Json;
...
public Car
{
  public int Year{ get; set; }
  public String Make{ get; set; }
}
...
JsonConvert.DeserializeObject<Car>(json)

我想验证年份是< 2017 && >=1900,例如.
或者,可能要确保Make是一个非空字符串(或它是一个可接受的值).

I want to validate that the year is < 2017 && >=1900, (for example).
Or maybe make sure that the Make is a non empty string, (or it is an acceptable value).

我知道我可以在反序列化之后添加Validate()类型的函数 ,但是我很好奇是否有一种方法可以与JsonConvert.DeserializeObject<Car>(json)

I know I could add a Validate() type function after I deserialize, but I am curious if there was a way of doing it at the same time as the JsonConvert.DeserializeObject<Car>(json)

推荐答案

可能合适的工具是只需创建一个Validate方法并在其上拍一个[OnDeserialized]属性:

Just create a Validate method and slap on it an [OnDeserialized] attribute:

public Car
{
  public int Year{ get; set; }
  public String Make{ get; set; }

  [OnDeserialized]
  internal void OnDeserializedMethod(StreamingContext context)
  {
    if (Year > 2017 || Year < 1900)
      throw new InvalidOperationException("...or something else");
  }
}

这篇关于在调用DeserializeObject&lt; Object&gt;(...)时验证Json数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆