【发布时间】:2020-12-07 08:01:39
【问题描述】:
我正在尝试使用 c# 中的一些简单 JSON 正文执行 POST 请求。我正在使用 HttpClient 来执行请求。我正在尝试以下方法:
using (var httpClient = new HttpClient { BaseAddress = baseAddress })
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", cred.Access_token);
var json = JsonConvert.SerializeObject("{'filter' : {'updated_since' : '2020-12-05T13:11:19+00:00'}}");
var data = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage httpResponseMessage = await httpClient.PostAsync("invoices.list", data).ConfigureAwait(false);
...
}
我在 JSON 字符串中添加了一个简单的过滤器,但结果过滤器不起作用,我得到了所有结果。当我在 Postman 中尝试相同的操作时,一切正常。所以我认为JSON字符串存在一些问题。
邮递员中的 JSON:
{
"filter": {
"updated_since": "2020-12-05T13:11:19+00:00"
}
}
我在这里做错了吗?
【问题讨论】:
-
json不是你想象的那样。很大程度上是因为您没有序列化 object。您正在序列化一个 string. -
我怀疑你的意思是这样的:
var json = JsonConvert.SerializeObject(new { filter = new { updated_since = "2020-12-05T13:11:19+00:00" }}); -
@mjwills,谢谢!我确实忘记了对字符串进行序列化。它现在就像我想要的那样工作。谢谢。
-
I indeed forgot to Serialize the string.好吧,更重要的是您将其序列化 两次 - 但您得到它的工作真是太棒了。 -
您根本不需要使用序列化,因为您拥有的字符串实际上是有效的 JSON,可以直接传递。
标签: c# json post httpclient