Reputation: 792
I have several projects in my solution. Here are 2 of them:
Entities contains DTOs(Data Transfer Objects) for my API. I need to provide my own JSON field names for DTOs. I came across this question, so i tried to use JsonPropertyNameAttribute, which is provided by System.Text.Json (.net core 3) and it does not work.
What do i need to do to specify custom JSON field names? Change the Entities project type to netcoreapp3.1 (then there are problems with other .net standard 2.0 libraries)? Use a different way of specifying custom JSON field names for DTO (i do not want to use Newtonsoft.Json because i heard that it has compatibility issues with .net core 3+ asp web APIs)?
Update: As strickt01 pointed, there is NuGet package that provides System.Text.Json serialization and deserialization for other .net versions, such as:
Upvotes: 1
Views: 1109
Reputation: 4048
If you don't want to use Newtonsoft.Json (by setting it as the default serializer in your .net core 3 project) then you do hit the catch 22 you've identified. However if your custom names all follow the same format then you can set a custom naming policy for the System.Text.Json serializer. i.e.
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNamingPolicy = new PascalToUnderscoreNamingPolicy(),
});
...with PascalToUnderscoreNamingPolicy
being a class overriding JsonNamingPolicy.ConvertName
in order to convert the likes of "CreationDate" to "creation_date".
Upvotes: 1