当缺少属性时,如何强制System.Text.Json序列化程序引发异常? [英] How to force System.Text.Json serializer throw exception when property is missing?
问题描述
Json.NET行为可以通过属性定义:使用默认值,或者如果json有效负载不包含必需的属性,则抛出异常.
Json.NET behaviour could be defined by attributes: either use default or just throw an exception if json payload does not contain required property.
但是System.Text.Json
序列化程序无任何作用.
上课:
Yet System.Text.Json
serializer silently does nothing.
Having class:
public sealed class Foo
{
[Required]
public int Prop {get;set;} = 10;
}
反序列化空对象:
JsonSerializer.Deserialize<Foo>("{}");
我只是使用Prop=10
获得了Foo
的实例.
我在 JsonSerializerOptions
强制其引发异常.有可能吗?
I simply get an instance of Foo
with Prop=10
.
I could not find any setting in JsonSerializerOptions
to force it throw an exception. Is it possible?
推荐答案
如果未接收到目标类型的属性之一的值,System.Text.Json不会引发异常.您需要实现一个自定义转换器.
System.Text.Json doesn't throw an exception if no value is received for one of the properties of the target type. You need to implement a custom converter.
这篇关于当缺少属性时,如何强制System.Text.Json序列化程序引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!