我如何允许空值被我的WebAPI模型接受? [英] How can I allow nulls to be accepted by my WebAPI model?

查看:145
本文介绍了我如何允许空值被我的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; }
}

来自我的客户端的数据如下:

The data coming from my client looks like this:

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

如果可能有些模型类需要修改我的模型类, 数据可能不存在,如果是这样,那我该如何修改IList?

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 ?

推荐答案

如果您要反序列化的字段是

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.

如果作为空值传输的值是引用类型,无需更改任何内容,因为引用类型可以为null.反序列化JSON时,该值将保持为空.

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.

例如,假设TestQuestionId在您的JSON中为空:

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

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

如果要正确反序列化该JSON,则必须将TestQuestionId声明为Nullable<int>,如下所示:

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

修改

简单明了:不能为值类型(int,uint,double,sbyte等)分配空值,这就是为什么发明了Nullable<T>(又称Nullable类型)的原因.可以为引用类型(字符串,自定义类)分配一个空值.

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.

这篇关于我如何允许空值被我的WebAPI模型接受?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆