C# 我如何允许我的WebAPI模型接受空值?
我有以下模型类:C# 我如何允许我的WebAPI模型接受空值?,c#,asp.net,asp.net-mvc,asp.net-web-api,C#,Asp.net,Asp.net Mvc,Asp.net Web Api,我有以下模型类: public class UserData { public IList<bool> Checked { get; set; } public IList<int> Matches { get; set; } public int TestQuestionId { get; set; } public string Text { get; set; } } 如果可能的话,我需要修改我的模型类吗 数据可能不存在,如果存在,
public class UserData
{
public IList<bool> Checked { get; set; }
public IList<int> Matches { get; set; }
public int TestQuestionId { get; set; }
public string Text { get; set; }
}
如果可能的话,我需要修改我的模型类吗
数据可能不存在,如果存在,那么我如何修改IList?如果您尝试反序列化的字段是,并且您的JSON显示其
null
,则需要将其更改为字段
如果作为null传输的值是,则无需更改任何内容,因为引用类型可以为null。反序列化JSON时,该值将保持为null
例如,假设JSON中的TestQuestionId
为空:
{
"Checked": [true,true,false,false,false,false],
"Matches": null,
"TestQuestionId": null,
"Text":null
}
如果您想正确地反序列化该JSON,则必须将TestQuestionId
声明为Nullable
,如下所示:
{"Checked":[true,true,false,false,false,false],"Matches":null,"TestQuestionId":480,"Text":null}
public class UserData
{
public IList<bool> Checked { get; set; }
public IList<int> Matches { get; set; }
public int? TestQuestionId { get; set; }
public string Text { get; set; }
}
公共类用户数据
{
公共IList已选中{get;set;}
公共IList匹配{get;set;}
public int?TestQuestionId{get;set;}
公共字符串文本{get;set;}
}
编辑
简单明了:不能为值类型(int、uint、double、sbyte等)分配空值,这就是为什么
Nullable
(也称为Nullable类型)被发明的原因。引用类型(字符串、自定义类)可能会被分配一个空值。到底什么不起作用?问题是什么还不清楚。您希望哪些字段为空?实际上,除testQuestionId之外的任何字段都可以为空,因此对于IList而言,字符串没有空等价物?您所说的“空等价物”是什么意思?IList可以为null。@SamanthaJIList
是可为null的类型,因此不需要显式的可为null的声明,但是int
不是,默认情况下它是一个值类型,这就是为什么它需要显式的可为null的声明。@SamanthaJ只有C#值类型必须显式标记为可为null。任何其他类型都可以为null,而无需显式标记,请参见:摘录:与引用类型不同,值类型不能包含null值。但是,可为null的类型功能允许将值类型分配给null。