Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change json field name on api controller answer

Let's say I have a controller with a get method:

[HttpGet]
public Car Get()
{
    return new Car() { Color = "Yellow" };
}

And also defined the Car class

public class Car {
   [JsonProperty(PropertyName = "TheColorIs")]
   public string Color {get;set;}
}

The client is receiving something like this in json format: { "Color": "Yellow" } Why isn't the property name in the json response "TheColorIs" ? Thanks

like image 739
Cadmi Avatar asked Jun 22 '26 03:06

Cadmi


1 Answers

I guess you are using ASP.NET Core 3.x which using System.Text.Json instead of Newtonsoft.Json . So that you should use JsonPropertyNameAttribute Class from System.Text.Json.Serialization namespace :

public class Car
{
    [JsonPropertyName("TheColorIs")]
    public string Color { get; set; }
}
like image 189
Nan Yu Avatar answered Jun 24 '26 18:06

Nan Yu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!