[英]How can I allow nulls to be accepted by my WebAPI model?
我有以下模型類:
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; }
}
來自我的客戶端的數據如下所示:
{"Checked":[true,true,false,false,false,false],"Matches":null,"TestQuestionId":480,"Text":null}
如果某些數據可能不存在,是否需要修改我的模型類,如果是的話,我該如何修改IList?
如果您要反序列化的字段是Value Type ,並且您的JSON表示其為null
,那么您需要將其更改為Nullable字段。
如果要傳遞為null的值是Reference Type ,則無需更改任何內容,因為Reference Type可以為null。 反序列化JSON時,該值將保持為null。
例如,假設您的JSON中的TestQuestionId
為null:
{
"Checked": [true,true,false,false,false,false],
"Matches": null,
"TestQuestionId": null,
"Text":null
}
如果要正確反序列化該JSON,則必須將TestQuestionId
聲明為Nullable<int>
,如下所示:
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; }
}
編輯
簡單明了:不能為值類型(int,uint,double,sbyte等)分配空值,這就是為什么發明了Nullable<T>
(又名Nullable類型)的原因。 可以為引用類型(字符串,自定義類)分配一個空值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.