【问题标题】:Change json field name on api controller answer更改 api 控制器答案上的 json 字段名称
【发布时间】:2020-07-08 11:05:05
【问题描述】:
假设我有一个带有 get 方法的控制器:
[HttpGet]
public Car Get()
{
return new Car() { Color = "Yellow" };
}
并且还定义了 Car 类
public class Car {
[JsonProperty(PropertyName = "TheColorIs")]
public string Color {get;set;}
}
客户端以 json 格式接收如下内容:
{
“颜色”:“黄色”
}
为什么 json 响应中的属性名称不是 "TheColorIs" ?
谢谢
【问题讨论】:
标签:
c#
asp.net-core
decorator
【解决方案1】:
我猜你正在使用 ASP.NET Core 3.x,它使用 System.Text.Json 而不是 Newtonsoft.Json 。所以你应该使用来自System.Text.Json.Serialization命名空间的JsonPropertyNameAttribute类:
public class Car
{
[JsonPropertyName("TheColorIs")]
public string Color { get; set; }
}
【解决方案2】:
我认为 Attribute 类型与您的序列化器类型不匹配,就像您使用 System.Text.Json.JsonSerializer,但是您使用 Newtonsoft.Json.JsonProperty。