How can I allow nulls to be accepted by my WebAPI

2019-07-19 13:44发布

I have the following Model Class:

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

The data coming from my client looks like this:

{"Checked":[true,true,false,false,false,false],"Matches":null,"TestQuestionId":480,"Text":null}

Do I need to modify my model class if it is possible that some of the data may not be present and if so then how could I modify the IList ?

1条回答
Summer. ? 凉城
2楼-- · 2019-07-19 14:17

If the field you are trying to deserialize is a Value Type, and your JSON says its null, then you need to change it to a Nullable field.

If the value being transferred as null is a Reference Type, there isn't a need to change anything, as a Reference Type can be null. When deserializing the JSON, the value will remain null.

For example, lets say TestQuestionId was null in your JSON:

{
   "Checked": [true,true,false,false,false,false],
   "Matches": null,
   "TestQuestionId": null,
   "Text":null
}

If you wanted to deserialize that JSON properly, you would have to declare TestQuestionId as a Nullable<int>, like this:

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

Edit

To make it simple and clear: Value Types (int, uint, double, sbyte, etc) cannot be assigned a null value, that is why Nullable<T> (A.K.A Nullable Types) were invented. Reference Types (string, custom classes) may be assigned a null value.

查看更多
登录 后发表回答