【问题标题】:net core web api json serialization - need fields prefixed with $net core web api json 序列化 - 需要以 $ 为前缀的字段
【发布时间】: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?

【问题讨论】:

    标签: c# asp.net-core json-serialization


    【解决方案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?

      【讨论】:

        猜你喜欢
        • 2023-03-24
        • 2018-04-23
        • 1970-01-01
        • 1970-01-01
        • 2021-04-01
        • 1970-01-01
        • 2019-09-06
        • 2020-11-18
        • 1970-01-01
        相关资源
        最近更新 更多