2014-07-21 67 views
1

我有以下型號類別:我如何允許我的WebAPI模型接受空值?

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?

+2

什麼是不工作?目前尚不清楚問題是什麼。 – David

+0

你希望哪個字段爲空? –

+0

其實除了testQuestionId以外的任何字段都可以爲空 –

回答

2

如果您試圖反序列化的字段是Value Type,並且您的JSON表示它的null,那麼您需要將其更改爲Nullable字段。

如果作爲空值傳輸的值是Reference Type,則不需要更改任何內容,因爲引用類型可以爲null。當反序列化JSON時,值將保持爲空。

例如,讓我們說TestQuestionId在你的JSON空:

{ 
    "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; } 
} 

編輯

爲了簡單明瞭:Valu e類型(int,uint,double,sbyte等)不能被分配一個空值,這就是爲什麼要發明Nullable<T>(A.K.A Nullable Types)的原因。引用類型(字符串,自定義類)可以分配一個空值。

+0

因此,IList 與字符串沒有等效關係? –

+0

「null null」是什麼意思? IList 可能爲空。 –

+0

@SamanthaJ'IList'是可以爲空的類型,所以不需要顯式可爲空的聲明,但「int」不是,默認情況下它是一個值類型,這就是爲什麼它需要顯式可爲空的聲明。 –