2017-02-16 19 views
1

我想在反序列化它之後驗證Json代碼。
例如,如果我有...在調用DeserializeObject時驗證Json數據<Object>(...)

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

我想驗證這一年是< 2017 && >=1900,(例如)。
或者可能確保Make是一個非空字符串,(或者它是一個可接受的值)。

我知道我可以我反序列化後添加Validate()型功能,但我很好奇,如果有在同一時間爲JsonConvert.DeserializeObject<Car>(json)

回答

1

可能是這個職位的最佳工具是serialization callback

只需創建一個Validate方法,並在其上拍的[OnDeserialized]屬性:

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

做它與二傳手將其插入的方式。

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; 
     } 
    } 
} 

對於整個對象的驗證,只是驗證任何時候一個值被設置。

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"); 
    } 
} 
+0

謝謝,但如果這兩個值相關的什麼,例如,如果'year'範圍取決於'make'或類似的東西。我幾乎不得不等待所有的值被設置。 – FFMG

+0

然後編寫一個調用程序,調用是否提供所有數據。 –

+0

我寧願有'DataAnnotations'可以在完全構建後用於驗證汽車,或者只是一個名爲'ValidateCar'的方法,它可以運行反序列化後需要執行的任何邏輯。讓你的setters運行邏輯可能會變得很亂。 – Jonesopolis