使用 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
(“Required property 'Value' expects a value but got null.Path '', line 1, position 16."):
void Main()
{
string json = @"{'Value': null }";
Demo res = JsonConvert.DeserializeObject<Demo>(json);
}
class Demo
{
[JsonProperty(Required = Required.Always)]
public string Value { get; set;}
}
关于c# - 使用 Json.NET 序列化 : how to require a property not being null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42808362/