c# - 使用 Json.NET 序列化 : how to require a property not being null?

标签 c# json serialization json.net

使用 Newtonsoft 的 Json.NET 序列化程序,是否可以要求属性包含非空值并在不是这种情况时抛出序列化异常?像这样的东西:

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

我知道可以在反序列化时执行此操作(使用 JsonPropertyRequired 属性),但我找不到关于此的任何序列化内容。

最佳答案

现在可以通过设置 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/

相关文章:

c# - void Start() 未被调用

javascript - BitGO - 从对象数组中获取帐户和值(value)

java - 反序列化 json 对象的嵌套数组返回 null

c# - XMLAttribute 不工作

c# - 如何将 UTF-8 阿拉伯字母转换为 CodePage 1001?

c# - 在 switch 语句中使用标识字段

jquery - jQuery 是否有内置的 JSON 支持?

java - Java 和 Python 之间的 XML 序列化库互操作性

c# - 数据数组的自定义序列化

java - 通过套接字多次发送序列化对象