如何在json body请求中传递null值给key

ktecyv1j  于 2023-03-31  发布在  其他
关注(0)|答案(2)|浏览(211)

我想在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
}

请帮帮我。

xdnvmnnf

xdnvmnnf1#

为了回答你的问题,要为null值写一个文本,你可以这样做:

var result = "my value is " + (strValue ?? "null");

或添加引号

var result = "my value is " + (strValue == null ? "null" : $"\"{strValue}\"");

你也可以创建一个静态的helper方法来简化

static string write(string str) => str == null ? "null" : $"\"{str}\"";
static string write(long? value) => value == null ? "null" : value.ToString();

在你的例子中,它变成了:

string postData = "{\"ID\":" + idvalue + ",\"TextKey\":" + write(textkeyvalue) + ",\"Exp\":" + write(expvalue) + ",\"TeamID\":" + write(teamIDvalue) + "}";

更好的解决方案!

为数据模型创建一个类,并使用一个库(例如System.Text.Json)来序列化它,如下所示:

public class MyData
{
   public long ID { get; set; }
   public string TextKey { get; set; }
   public string Exp { get; set; }
   public long? TeamID { get; set; }
}

//construct model
var data = new MyData()
{
   ID = 162617,
   TextKey = "107737",
   Exp = null,
   TeamID = null,
}

//serialize to json
var result = System.Text.Json.JsonSerializer.Serialize(data);
ej83mcc0

ej83mcc02#

@gepa的答案是正确的,但你也可以序列化一个匿名对象:

long idvalue = 162617;
string textkeyvalue = "107737";
string? expvalue = null;
long? teamIDvalue = null;

string postData = System.Text.Json.JsonSerializer.Serialize(new 
{
    ID = idvalue,
    TextKey = textkeyvalue,
    Exp = expvalue,
    TeamID = teamIDvalue,
});

相关问题