在Json.NET中,如何在反序列化时使所有属性成为必需?我知道我可以使用消息上的属性来执行此操作,但我不想这样做.主要是因为它需要我的消息库来承担外部依赖.
我尝试了MissingMemberHandling.Error设置,但它与我想要的相反.我对JSON有额外的属性没关系.我希望它在JSON中缺少任何目标对象属性时失败.
我实际上反序列化为F#记录,无论如何,属性通常不能为null. (它们不能通过代码中的常规方式赋值为null.)但是当数据丢失时,Json.NET很乐意将属性默认为null.
接受答案的F#版本
分解器
open System open Newtonsoft.Json open Newtonsoft.Json.Serialization type RequireAllPropertiesContractResolver() = inherit DefaultContractResolver() override me.CreateObjectContract(objectType:Type) = let contract = base.CreateObjectContract(objectType) contract.Itemrequired <- new Nullable<required>(required.Always) contract
在设置中
let settings = new JsonSerializerSettings() // default settings ... settings.ContractResolver <- new RequireAllPropertiesContractResolver()
将属性
[JsonObject(ItemRequired=Required.Always)]
添加到您的类:
Type: 07001
A value indicating whether the object’s properties are required.
required的可能值为:
- Default: The property is not required. The default state.
- AllowNull: The property must be defined in JSON but can be a null value.
- Always: The property must be defined in JSON and cannot be a null value.
该设置是继承的,因此可以添加到通用基类中.
更新
要对所有对象进行全局操作,请将DefaultContractResolver
子类化,并将Itemrequired标志添加到所有对象协定:
public class RequireObjectPropertiesContractResolver : DefaultContractResolver { protected override JsonObjectContract CreateObjectContract(Type objectType) { var contract = base.CreateObjectContract(objectType); contract.Itemrequired = required.Always; return contract; } }
然后,在设置中:
var settings = new JsonSerializerSettings { ContractResolver = new RequireObjectPropertiesContractResolver() };