2017-03-15 23 views
2

使用Newtonsoft的Json.NET序列化程序,是否可以要求屬性包含非空值並在序列化時拋出異常(如果不是這種情況)?喜歡的東西:用Json.NET序列化:如何要求屬性不爲null?

public class Foo 
{ 
    [JsonProperty("bar", SerializationRequired = SerializationRequired.DisallowNull)] 
    public string Bar { get; set; } 
} 

我知道這是可能做到這一點在反序列化(使用JsonPropertyRequired財產),但我找不到序列化這個事情。

+0

你走線槽這個http://www.newtonsoft.com/json/help/html/SerializationErrorHandling.htm?最後,它提到你可以添加一個內部的OnError方法到Foo類,你可以在其中指定請求的行爲。 – pijemcolu

回答

0

正在關注Newtonsoft serialization error handling documentation您可以在OnError()方法中處理null屬性。我不完全確定你將作爲NullValueHandling參數傳遞給SerializeObject()。

public class Foo 
{ 
    [JsonProperty] 
    public string Bar 
    { 
     get 
     { 
      if(Bar == null) 
      { 
       throw new Exception("Bar is null"); 
      } 
      return Bar; 
     } 
     set { Bar = value;} 

    [OnError] 
    internal void OnError(StreamingContext context, ErrorContext errorContext) 
    { 
      // specify that the error has been handled 
      errorContext.Handled = true; 
      // handle here, throw an exception or ... 
    } 
} 


int main() 
{ 
    JsonConvert.SerializeObject(new Foo(), 
         Newtonsoft.Json.Formatting.None, 
         new JsonSerializerSettings { 
          NullValueHandling = NullValueHandling.Ignore 
         }); 
} 
+0

哈!這是行得通的,但是要做到這一點很重要......我寧願編寫自己的驗證器/驗證屬性,然後在序列化之前調用它! –

+0

管道工需求 - > https://www.theguardian.com/business/2015/feb/10/uk-plumbers-builders-engineers-skill-crisis-economy – pijemcolu

相關問題