[英]Serializing with Json.NET: how to require a property not being null?
使用 Newtonsoft 的 Json.NET 序列化程序,是否可以要求屬性包含非空值並在序列化時拋出異常(如果不是這種情況)? 就像是:
public class Foo
{
[JsonProperty("bar", SerializationRequired = SerializationRequired.DisallowNull)]
public string Bar { get; set; }
}
我知道可以在反序列化時執行此操作(使用JsonProperty
的Required
屬性),但是我找不到任何關於序列化的內容。
這是現在可以通過設定JsonPropertyAttribute
到Required.Always
。
這需要 Newtonsoft 12.0.1+,在提出此問題時該版本尚不存在。
下面的示例拋出一個JsonSerializationException
(“必需的屬性 'Value' 需要一個值,但為空。路徑 '',第 1 行,位置 16。”):
void Main()
{
string json = @"{'Value': null }";
Demo res = JsonConvert.DeserializeObject<Demo>(json);
}
class Demo
{
[JsonProperty(Required = Required.Always)]
public string Value { get; set;}
}
按照Newtonsoft 序列化錯誤處理文檔,您可以在 OnError() 方法中處理空屬性。 我不完全確定您會將什么作為 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
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.