Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate Json data while calling DeserializeObject<Object>( ... )

Tags:

json

c#

json.net

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)

like image 611
FFMG Avatar asked Mar 13 '26 23:03

FFMG


2 Answers

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");
  }
}
like image 76
A. Chiesa Avatar answered Mar 15 '26 12:03

A. Chiesa


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");
    }
}
like image 26
Silas Reinagel Avatar answered Mar 15 '26 14:03

Silas Reinagel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!