C# net核心web api json序列化-需要前缀为$
我正在使用net core web api,需要返回一个属性名为“$skip”的负载。我尝试使用DataAnnotations:C# net核心web api json序列化-需要前缀为$,c#,asp.net-core,json-serialization,C#,Asp.net Core,Json Serialization,我正在使用net core web api,需要返回一个属性名为“$skip”的负载。我尝试使用DataAnnotations: public class ApiResponseMessage { [Display(Name ="$skip", ShortName = "$skip")] public int Skip { get; set; } [Display(Name = "$top", ShortName = "$top")] public int Top
public class ApiResponseMessage
{
[Display(Name ="$skip", ShortName = "$skip")]
public int Skip { get; set; }
[Display(Name = "$top", ShortName = "$top")]
public int Top { get; set; }
}
在我的控制器中,我只使用
return Json(payload)
但是,我的响应负载如下所示:
"ResponseMsg": {
"Skip": 0,
"Top": 3
}
我需要的是:
"ResponseMsg": {
"$skip": 0,
"$top": 3
}
解决这个问题的最佳选择是什么?
是否需要编写自己的ContractResolver或Converter?使用
JsonProperty
属性设置自定义属性名称:
[JsonProperty(PropertyName = "$skip")]
public int Skip { get; set; }
输出:
{ "$skip": 1 }
更多信息:ASP.NET核心已经使用JSON.NET作为其基础JavaScriptSerializer 这是依赖关系 Microsoft.AspNetCore.Mvc-->Microsoft.AspNetCore.Formatter.Json-->Microsoft.AspNetCore.JsonPatch-->Newtonsoft.Json 像这样的对象的示例装饰将实现此目标
[JsonObject]
public class ApiResponseMessage
{
[JsonProperty("$skip")]
public int Skip { get; set; }
[JsonProperty("$top")]
public int Top { get; set; }
....
}
从.net core 3.0开始,该框架现在使用System.Text.Json。您可以使用
[JsonPropertyName("htmlid")]
public string HtmlId { get; set; }
请参见感谢您显示依赖路径;这就是能够找到实际使用的Newtonsoft.Json版本的原因(我当前的设置是10.0.1)