12

我正在使用 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 吗?

4

3 回答 3

16

从 .net core 3.0 开始,该框架现在使用 System.Text.Json。你可以在你的类中装饰一个 json 属性

[JsonPropertyName("htmlid")]
public string HtmlId { get; set; }

请参阅System.Text.Json

于 2019-06-25T23:52:48.357 回答
6

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; }

    ....
}
于 2017-06-27T17:38:54.787 回答
3

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

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

输出:

{ "$skip": 1 }

更多信息:使用 Json.net 序列化时如何更改属性名称?

于 2017-06-27T17:18:24.030 回答