英文:
PostAsJsonAsync ignoring JsonProperty name attribute
问题
The first method is not working because it uses client.PostAsync(path, null, ct)
when value
is null, and this does not include any JSON data in the request body. Therefore, the JsonProperty(Name)
attribute is ignored because there is no JSON data to serialize.
The second method works because it explicitly serializes the value
object to JSON using JsonConvert.SerializeObject(value)
and then creates a StringContent
object with the serialized JSON. This ensures that the JSON data is included in the request body, and the JsonProperty(Name)
attribute is respected.
If you prefer to use the first method, you would need to modify it to include the JSON data explicitly when value
is not null, similar to how the second method does it.
英文:
I have a static method that posts data as follows:
public static Task<HttpResponseMessage> PostExAsync<TValue>(this HttpClient client, string path, TValue value, CancellationToken ct = default)
{
if (value == null)
{
return client.PostAsync(path, null, ct);
}
return client.PostAsJsonAsync(path, value, ct);
}
With the above code, the JsonProperty(Name)
attribute is ignored. If I change the code as follows:
public static Task<HttpResponseMessage> PostExAsync<TValue>(this HttpClient client, string path, TValue value, CancellationToken ct = default)
{
var json = value != null ? JsonConvert.SerializeObject(value) : null;
var content = value != null ? new StringContent(json, Encoding.UTF8, "application/json") : null;
return client.PostAsync(path, content, ct);
}
It works. But why is the first method not working? I would rather use the first method instead of the second.
答案1
得分: 3
这是因为 PostAsJsonAsync
使用了 System.Text.Json
库,该库具有自己的属性:JsonPropertyNameAttribute
。
在第二个示例中,您正在使用 JSON.NET,因此考虑到它按您的期望工作,似乎您的模型已用 JsonPropertyAttribute
装饰。
如果您想在使用模型的所有地方都使用 System.Text.Json,那么您应该能够只是更改属性为来自 System.Text.Json 的属性。否则,您可能可以为两个库装饰您的属性/属性。
英文:
The reason for this is that PostAsJsonAsync
uses the System.Text.Json
library, which has its own attribute: JsonPropertyNameAttribute
.
In your second example, you're using JSON.NET, so given that it's working as you expect, it seems that your model is decorated with JsonPropertyAttribute
.
If you want to use System.Text.Json everywhere that the model is used, then you should be able to just change your attributes to the ones from System.Text.Json. Otherwise, you could potentially decorate your property/properties with attributes for both libraries.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论