更改 api 控制器答案上的 json 字段名称

Cad*_*dmi 3 c# decorator asp.net-core

假设我有一个带有 get 方法的控制器:

[HttpGet]
public Car Get()
{
    return new Car() { Color = "Yellow" };
}
Run Code Online (Sandbox Code Playgroud)

并且还定义了 Car 类

public class Car {
   [JsonProperty(PropertyName = "TheColorIs")]
   public string Color {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

客户端收到类似 json 格式的内容: { "Color": "Yellow" } 为什么 json 响应中的属性名称不是 "TheColorIs" ?谢谢

Nan*_* Yu 6

我猜您正在使用 ASP.NET Core 3.x,它使用System.Text.Json而不是Newtonsoft.Json. 所以你应该使用命名空间JsonPropertyNameAttribute中的类System.Text.Json.Serialization

public class Car
{
    [JsonPropertyName("TheColorIs")]
    public string Color { get; set; }
}
Run Code Online (Sandbox Code Playgroud)