我想在API中使用post请求将一个null值传递给一个键。
例如,我想传递下面的json数据。即Exp和TeamID为null
{
"ID":162617,
"TextKey":"107737",
"Exp":null,
"TeamID":null
}
结果在postman中被接受,但是当我尝试使用下面的c#代码传递相同的结果时,我的json变得无效
long idvalue = 162617;
string textkeyvalue = "107737";
string expvalue = null;
long? teamIDvalue = null;
string postData = "{\"ID\":" + idvalue + ",\"TextKey\":\"" + textkeyvalue + "\",\"Exp\":\"" + expvalue + "\",\"TeamID\":\"" + teamIDvalue + "\"}";
这给了我以下输出。
{
"ID":162617,
"TextKey":"107737",
"Exp":"",
"TeamID":
}
我的请求由于无效的json body而失败。那么我如何传递这种类型的null数据或null关键字?
注意:-所有的键值对在我的API中都是强制性的,所以如果它们为空,我不能省略它们。
我只想以下面的格式传递数据。
{
"ID":162617,
"TextKey":"107737",
"Exp":null,
"TeamID":null
}
请帮帮我。
2条答案
按热度按时间xdnvmnnf1#
为了回答你的问题,要为null值写一个文本,你可以这样做:
或添加引号
你也可以创建一个静态的helper方法来简化
在你的例子中,它变成了:
更好的解决方案!
为数据模型创建一个类,并使用一个库(例如System.Text.Json)来序列化它,如下所示:
ej83mcc02#
@gepa的答案是正确的,但你也可以序列化一个匿名对象: