Search code examples
c#jsonasp.net-core-webapisystem.text.json

Using another name in response when deserializing json in ASP.NET Core 8 Web API


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:

  1. read a json as a string in WEB API
  2. then deserialize it to class FooDto and 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?


Solution

  • For your requirement, just remove the [JsonPropertyName] attribute and only use the following code can achieve. Also be sure you do not configure anything about Serialization/Deserialization in Program.cs:

    string json = "{\r\n    \"product_id\": 1\r\n}";
    
    JsonSerializerOptions serializeOptions = new ()
    {
        PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
        WriteIndented = true
    };
    JsonSerializer.Deserialize<FooDto>(json, serializeOptions);