12

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?

3 Answers 3

17

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

Sign up to request clarification or add additional context in comments.

Comments

6

ASP.NET Core already uses JSON.NET as its base JavaScriptSerializer.

Here is the dependency.

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

    ....
}

1 Comment

Thank you for showing that dependency path; that was what enabled to find what version of Newtonsoft.Json is actually in use (10.0.1 for my current setup)
3

Use JsonProperty attribute to set a custom property name:

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

Output:

{ "$skip": 1 }

More info: How can I change property names when serializing with Json.net?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.