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?
For DotnetCore3.1 We can use
By using custom converter you will be able to achieve what you need.
The following suite of components based on attributes might suit your needs and is quite generic in case you want to expand it.
Base attribute class
Defines the
IsMatch
which allows you to define if the object property matches the json property.Sample implementation: multi deserialization names
Defines an attribute which allows you to have multiple names associated to a property. The
IsMatch
implementation simply loops through them and tries to find a match.The Converter in order to bind both attributes to the json deserialization the following converter is required:
Sample using the codes pasted above, and by decorating the class as follow, I managed to get the objects to deserialize properly:
Output 1
Output 2
Output 3
In My Case, I don't want to change property name
Carrier
&TrackingNumber
so I just add
new JsonSerializerSettings()
on JsonResult responseWithout using
JsonSerializerSettings
OutputWith using
JsonSerializerSettings
OutputI think that this should work too:
Change your package class and add JsonProperty decoration for each field you wish to map to a different json field.
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:Hope it helps!