ASP.Net Core 2.2允许使用MvcJsonOptions.SerializerSettings
属性设置序列化程序设置。问题在于它同时影响输入和输出。有没有办法为输入(反序列化)和输出(序列化)提供单独的选项?特别是,我需要为NullValueHandling
设置设置不同的行为:反序列化客户端json时,对不可为空的字段忽略null错误,而在对结果进行序列化时,为已定义的模型字段保留null。
例如,我有一个用于请求的C#模型:
public class SomeEntity
{
public int Id { get; set; }
public int? ParentId { get; set; }
public string Name { get; set; }
}
并输入JSON:{ id: null, parentId: null, name: "test" }
。对于NullValueHandling.Include
,反序列化失败,但对于NullValueHandling.Ignore
有效。
但是当我序列化这样的实体时
new SomeEntity { Id = 1, ParentId = null, Name = "test" }
NullValueHandling.Include
:{ id: 1, parentId: null, name: "test" }
保持为空,但NullValueHandling.Ignore
:{ id: 1, name: "test" }
则将其擦除。
我需要实现输入的“忽略”方案和输出的“包含”方案。
ASP.Net Core 2.2允许使用MvcJsonOptions.SerializerSettings属性设置序列化程序设置。问题在于它同时影响输入和输出。是否有办法为...
我将使用Newtonsoft.Json的JsonSerializerSettings类定义两个实例mySerializeSetting和myDeserializeSettings。