0

I am using ASP.NET Core 3.1 Web API. I have the following response model:

public class UserModel
{
   public string UserId { get; set; }
   public string UserName { get; set; }
}

It produces the following json response:

{
    "userId": 1,
    "userName": "SomeName"
}

I am interested in is there any way to change the property names of output JSON without creating a new class? Also, I would like to apply this rule only for specific action and keep default property names for other actions. In our project, we stick to System.Text.Json Serializer. The desired JSON output:

{
    "teacherId": 1,
    "teacherName": "SomeName"
}
4
  • If the model contains only two properties, you could try anonymous type. Commented Oct 3, 2020 at 8:16
  • 2
    Create a TeacherModel - a teacher is more specific than a user, and so they represent different things. Commented Oct 3, 2020 at 8:44
  • Is it good practice to create a separate model for this if you just changing the names of properties? Commented Oct 3, 2020 at 18:56
  • If you ask yourself the question, "Should these two things be able to change independently?", and the answer is "yes", then yes, having two separate models is fine. Commented Oct 3, 2020 at 19:06

3 Answers 3

4

If you don't want to switch to Newtonsoft.JSON and use the default serializer, use [JsonPropertyName("name")]. You may find extensive information from Microsoft @ https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-customize-properties?pivots=dotnet-core-3-1

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

Comments

0

You can use JsonResult class from Microsoft.AspNetCore.Mvc namespace on Action.

return new JsonResult(new
        {
            TeacherId = userModel.UserId,
            TeacherName = userModel.UserName
        });

Comments

0
using Newtonsoft.Json;

public class UserModel
{
   [JsonProperty(PropertyName = "Foo")]
   public string UserId { get; set; }
   public string UserName { get; set; }
}

.net core 3.* doesn't work with Newtonsoft by default.

you should install Microsoft.AspNetCore.Mvc.NewtonsoftJson

and add it to your project

services.AddControllers().AddNewtonsoftJson();

2 Comments

The question's title indicates the change is only wanted for a specific action - this would apply to all actions that use UserModel.
For core 3 and net 5 default serializer [JsonPropertyName("name")] should be used.

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.