缺少属性时如何强制 System.Text.Json 序列化程序抛出异常? [英] How to force System.Text.Json serializer throw exception when property is missing?

查看:32
本文介绍了缺少属性时如何强制 System.Text.Json 序列化程序抛出异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

参考:https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to#required-properties

这篇关于缺少属性时如何强制 System.Text.Json 序列化程序抛出异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆