I am working with System.Text.Json
and need to map some elements of the json result with the properties of my entity. Some of these elements have the underscore character to separate words while my properties are in case pascal. I know I can use the JsonPropertyName
attribute to map the json element to my property, but I’m looking for a way to do this without using the JsonPropertyName
attribute.
Question posted in Json
Our archive of expertly curated questions and answers provides insights and solutions to common problems related to this popular data interchange format. From parsing and manipulating JSON data to integrating it with various programming languages and web services, our archive has got you covered. Start exploring today and take your JSON skills to the next level
Our archive of expertly curated questions and answers provides insights and solutions to common problems related to this popular data interchange format. From parsing and manipulating JSON data to integrating it with various programming languages and web services, our archive has got you covered. Start exploring today and take your JSON skills to the next level
2
Answers
You can use a custom naming policy with a serializer.
And define the naming conversation according to your underscore logic. (code provided below may not be precise to your use case as you didn’t specify the casing besides the underscores, but you should be able to build on top of it)
If you want to bind all Pascal-cased .NET properties to snake_cased JSON properties, you can use the
PropertyNamingPolicy
shown in the answer by Levan Goderdzishvili.If you only want to remap selected properties, in .NET 7 and later you may use a typeInfo modifier to customize your type’s contract.
First, define the following static method returning an
Action<JsonTypeInfo>
:And now if you have a model that looks like e.g.:
You will be able to serialize
SnakeCaseProperty
as"snake_case_property"
as by customizing aDefaultJsonTypeInfoResolver
as follows:E.g. for
Model
the resulting JSON will look like:Demo fiddle here.