首页 > 解决方案 > 列表未提供值时无法反序列化

问题描述

在类 Account 中,属性 Industry 是枚举类型 Industry 的集合

一个帐户可以属于多个行业的。

public class Account
{

[JsonProperty(ItemConverterType = typeof(StringEnumConverter))]
public List<Industry> Industrys { get; set; } 

}

Public enum Industry
{
AerospaceAirlines = 0,
            Agriculture = 1,
            Apparel = 2,
            Automotive = 3,
            Banking = 4,
            BioTechnology = 5,
            Chemicals = 6,
            Communications = 7,
            Construction = 8,
            Consultancy = 9,
            ConsumerDurables = 10,
            Education = 11,
}

创建新账户时,不强制添加行业。当此 Industrys 属性的请求对象中未提供任何值时,将失败。

反序列化出现错误“值不能为空。\r\n参数名称:源”

当默认绑定器尝试填充 accountModel 对象时会发生故障。

[HttpPost]
        public async Task<IActionResult> Post([FromBody]AccountModel accountModel)
        {
            if (accountModel == null)
            {
                throw new ApiException(ApplicationErrorCode.FieldRequiredError, "request cannot be empty");
            }
       }

如何允许发件人在没有提供行业的情况下发送请求?

标签: c#asp.net-corejson.net

解决方案


改变:

public class Account
{

[JsonProperty(ItemConverterType = typeof(StringEnumConverter))]
public List<Industry> Industrys { get; set; } 

}

到:

public class Account
{

[JsonProperty(ItemConverterType = typeof(StringEnumConverter))]
public List<Industry> Industrys { get; set; } = new List<Industry>();

}

推荐阅读