Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a .Net Core Web API. It automatically maps models when the model properties match the request body. For example, if you have this class:

public class Package
{
    public string Carrier { get; set; }
    public string TrackingNumber { get; set; }
}

It would correctly bind it to a POST endpoint if the request body is the following JSON:

{
    carrier: "fedex",
    trackingNumber: "123123123"
}

What I need to do is specify a custom property to map. For example, using the same class above, I need to be able to map to JSON if the TrackingNumber comes in as tracking_number.

How do I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
144 views
Welcome To Ask or Share your Answers For Others

1 Answer

TejSoft's answer does not work in ASP.NET Core 3.0 Web APIs by default.

Starting in 3.0, the ASP.NET Core Json.NET (Newtonsoft.Json) sub-component is removed from the ASP.NET Core shared framework. It is announced that, "Json.NET will continue to work with ASP.NET Core, but it will not be in the box with the shared framework." The newly added Json Api claimed to be specifically geared for high-performance scenarios.

Use JsonPropertyName attribute to set a custom property name:

using System.Text.Json.Serialization;

public class Package
{
    [JsonPropertyName("carrier")]
    public string Carrier { get; set; }

    [JsonPropertyName("tracking_number")]
    public string TrackingNumber { get; set; }
}

Hope it helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...