[英]net core web api json serialization - need fields prefixed with $
I'm using net core web api and need to return a payload with property name "$skip". 我正在使用net core web api,需要返回属性名为“$ skip”的有效负载。 I tried using the DataAnnotations: 我尝试使用DataAnnotations:
public class ApiResponseMessage
{
[Display(Name ="$skip", ShortName = "$skip")]
public int Skip { get; set; }
[Display(Name = "$top", ShortName = "$top")]
public int Top { get; set; }
}
In my Controller I simply use 在我的控制器中,我只是使用
return Json(payload)
However, my response payload looks like follow: 但是,我的响应有效负载如下所示:
"ResponseMsg": {
"Skip": 0,
"Top": 3
}
and I need it to be: 我需要它:
"ResponseMsg": {
"$skip": 0,
"$top": 3
}
What is the best option to address this? 解决这个问题的最佳选择是什么? Do I need to write my own ContractResolver or Converter? 我是否需要编写自己的ContractResolver或Converter?
ASP.NET Core already uses JSON.NET as its base JavaScriptSerializer. ASP.NET Core已经使用JSON.NET作为其基础JavaScriptSerializer。
Here is the dependency. 这是依赖。
Microsoft.AspNetCore.Mvc --> Microsoft.AspNetCore.Formatter.Json --> Microsoft.AspNetCore.JsonPatch --> Newtonsoft.Json Microsoft.AspNetCore.Mvc - > Microsoft.AspNetCore.Formatter.Json - > Microsoft.AspNetCore.JsonPatch - > Newtonsoft.Json
A sample decoration of the object like this would achieve the goal 像这样的对象的样本装饰将实现目标
[JsonObject]
public class ApiResponseMessage
{
[JsonProperty("$skip")]
public int Skip { get; set; }
[JsonProperty("$top")]
public int Top { get; set; }
....
}
Use JsonProperty
attribute to set a custom property name: 使用JsonProperty
属性设置自定义属性名称:
[JsonProperty(PropertyName = "$skip")]
public int Skip { get; set; }
Output: 输出:
{ "$skip": 1 }
More info: How can I change property names when serializing with Json.net? 更多信息: 如何在使用Json.net进行序列化时更改属性名称?
starting in .net core 3.0 the framework now uses System.Text.Json. 从.net core 3.0开始,框架现在使用System.Text.Json。 You can decorate a json attribute in your class with 您可以使用类修饰类中的json属性
[JsonPropertyName("htmlid")]
public string HtmlId { get; set; }
See System.Text.Json 请参见System.Text.Json
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.