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

查看:141
本文介绍了当缺少属性时,如何强制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/zh-cn/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to#required-properties

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

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