I am using System.Text.Json
in .NET 6 and I have some data classes that have properties annotated with JsonPropertyName
to be able to communicate with another API, but now I need to use the original properties names for another business reason and was looking for a way to make the serializer ignore those annotations and use the actual property names.
I've found that in Newtonsoft I could've used ContractResolver
to do it like suggested here, but I couldn't find an alternative in System.Text.Json
.
Now I am thinking of using DTOs to do it but I am looking for a simpler solution if it's available.
Here's a quick example, say we have this Account
class:
public class Account {
[JsonPropertyName("fname")]
public string FirstName { get; set; }
[JsonPropertyName("lname")]
public string LastName { get; set; }
[JsonPropertyName("years_old")]
public int Age {get; set; }
}
In one use I want the response sent to be of the format:
{
"fname": "John",
"lname": "Doe",
"years_old": 25
}
And in another response, I need:
{
"firstname": "John",
"lastname": "Doe",
"age": 25
}
Now this is just a sample, but my actual classes have a lot of properties, and making DTOs isn't for each use case is too much work. Hence why I am looking for a solution using something like Newtonsoft DefaultContractResolver
but using System.Text.Json
.
PS: I can't afford to move back to Newtonsoft.Json.