问题
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)
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).
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)
回答1:
Probably the right tool for the job is a serialization callback
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");
}
}
回答2:
Plug it in with the Setters.
public class Car
{
private int _year;
public int Year
{
get { return _year; }
set
{
if (_year > 2017 || _year < 1900)
throw new Exception("Illegal year");
_year = value;
}
}
}
For entire object validation, just validate anytime a value is set.
public class Car
{
private int _year;
private string _make;
public string Make
{
get { return _make; }
set
{
_make = value;
ValidateIfAllValuesSet();
}
}
public int Year
{
get { return _year; }
set
{
_year = value;
ValidateIfAllValuesSet();
}
}
private void ValidateIfAllValuesSet()
{
if (_year == default(int) || _make == default(string))
return;
if (_year > 2017 || _year < 1900)
throw new Exception("Illegal year");
}
}
来源:https://stackoverflow.com/questions/42283858/validate-json-data-while-calling-deserializeobjectobject