We are using ASP.NET Core 8 Web API. I have read this post, but I use System.Text.Json. So it is not duplicate question.
My goals are:
- read a json as a string in WEB API
- then deserialize it to class
FooDtoand return it to clients of WEB API.
I read the following json from database as a string:
{
"product_id": 1
}
The dto class looks like this:
public class FooDto
{
[JsonPropertyName("product_id")]
public long? ProductId { get; set; }
}
The code that I tried looks like this:
JsonSerializer.Deserialize<FooDto>(json);
In addition, I tried like this:
JsonSerializerOptions serializeOptions = new ()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
WriteIndented = true
};
JsonSerializer.Deserialize<FooDto>(json, serializeOptions);
However, the result of the response of the ASP.NET Core Web API 8 method looks like this:
{
"product_id": 1
}
But, the desired result should look like this. I mean, Web API should return the following result for clients:
{
"productId": 1
}
Is it possible to use C# property name when deserializing json?
[JsonPropertyName("productId")]. Whatever you define as an explicit annotation on the members of your class will override any naming applied by any conventions or serialization options{"product_id":1}from the db, but the API to return as{"productId":1}? If so, I am not sure that you can do it with a single class