ASP.Net Core 2.2-用于输入和输出的单独的序列化程序设置

问题描述 投票:0回答:1

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属性设置序列化程序设置。问题在于它同时影响输入和输出。是否有办法为...

c# .net asp.net-core json.net asp.net-core-2.2
1个回答
0
投票

我将使用Newtonsoft.Json的JsonSerializerSettings类定义两个实例mySerializeSetting和myDeserializeSettings。

© www.soinside.com 2019 - 2024. All rights reserved.