net core web api json 序列化 - 需要以 $ 为前缀的字段

Posted

技术标签:

【中文标题】net core web api json 序列化 - 需要以 $ 为前缀的字段【英文标题】:net core web api json serialization - need fields prefixed with $ 【发布时间】:2017-11-30 20:16:43 【问题描述】:

我正在使用 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  get; set; 

在我的控制器中我只是使用

return Json(payload)

但是,我的响应负载如下所示:

"ResponseMsg": 
    "Skip": 0,
    "Top": 3

我需要它是:

"ResponseMsg": 
    "$skip": 0,
    "$top": 3

解决这个问题的最佳选择是什么? 我是否需要编写自己的 ContractResolver 或 Converter?

【问题讨论】:

【参考方案1】:

从 .net core 3.0 开始,该框架现在使用 System.Text.Json。你可以用

在你的类中装饰一个 json 属性
[JsonPropertyName("htmlid")]
public string HtmlId  get; set; 

见System.Text.Json

【讨论】:

【参考方案2】:

ASP.NET Core 已经使用 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; 

    ....

【讨论】:

感谢您显示该依赖路径;这就是能够找到实际使用的 Newtonsoft.Json 版本(我当前设置为 10.0.1)的原因【参考方案3】:

使用JsonProperty 属性设置自定义属性名称:

[JsonProperty(PropertyName = "$skip")]
public int Skip  get; set; 

输出:

 "$skip": 1 

更多信息:How can I change property names when serializing with Json.net?

【讨论】:

以上是关于net core web api json 序列化 - 需要以 $ 为前缀的字段的主要内容,如果未能解决你的问题,请参考以下文章