net core web api json serialization - need fields prefixed with $

ericsson007 picture ericsson007 · Jun 27, 2017 · Viewed 10.3k times · Source

I'm using net core web api and need to return a payload with property name "$skip". I tried using the 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?

Answer

Jhonatas Kleinkauff picture Jhonatas Kleinkauff · Jun 26, 2019

starting in .net core 3.0 the framework now uses System.Text.Json. You can decorate a json attribute in your class with

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

See System.Text.Json