- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company

Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
How to change property names when serializing to Json in asp.Net
I have an MVC Web API Controller that exposes a method:
CustomClass is a really complex class wich contains several levels of objects of different classes. Objects from these classes are somehow built in another part of the code using a mapper that relies on Newtonsoft Json.
I just got a request to modify my code to change some of CustomClass property names (along the whole tree). My first approach was to create another set of classes, so I could have one for receiving data and other for exposing data with a converter in the middle but there are so many classes in the structure and they are so complex that it would consume a lot of effort. Also, during the process of converting from input to output classes, it would require twice the memory to hold 2 copies of the same exact data.
My second approach was using JsonProperty(PropertyName ="X") to change the resulting json BUT, as the input also relies in Newtonsoft Json, I completely broke the input process.
My next approach was to create a custom serializer and user [JsonConverter(typeof(CustomCoverter))] attribute BUT it changes the way CustomClass is serialized everywhere and I can't change the way the rest of the API responds, just some specific methods.
So, the question is... does anyone imagine a way to change the way my CustomClass is serialized just in certain methods ?
- asp.net-mvc
- asp.net-web-api
- Json.Net can read some pretty complex classes, I find it odd that Newtonsoft.Json library can't correctly serialize. Are you sure complexity is the cause and can you define the issue in a bit more detail. – Greg Oct 19, 2017 at 16:40
- 2 Use a custom contract resolver. See JSON.net ContractResolver vs. JsonConverter . – dbc Oct 19, 2017 at 16:41
- In fact, is this question a duplicate of JSON.net ContractResolver vs. JsonConverter ? We can't really provide a more concrete answer with code without some sample types. – dbc Oct 19, 2017 at 19:29
This is the final solution:
1) Created a custom Attribute and decorated the properties that I needed its name changed in the serialized Json:
2) Decordated the properties accordingly
3) Implemented a Custom Resolver using reflection to remap the property name for those properties decorated with MyCustomJsonPropertyAttribute
4) Implemented the method in the controller like this:
Thanks a lot to dbc for pointing me the way.
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged c# asp.net json asp.net-mvc asp.net-web-api or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- The [amazon] tag is being burninated
- Launching the CI/CD and R Collectives and community editing features for...
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
- Temporary policy: ChatGPT is banned
Hot Network Questions
- Atheists who follow the teachings of Jesus
- "We, who've been connected by blood to Prussia's throne and people since Düppel"
- will thumb also get callus on strumming guitar
- How can I explain to my manager that a project he wishes to undertake cannot be performed by the team?
- Tips for golfing in SVG
- Stats update during Index rebuild
- Transgenic Peach DNA Splicing
- How to insulate the neutral from the ground in a Subpanel Siemens mc1020b1100sz
- "Users & Groups" does not display groups on Ventura 13.2
- Does Cast a Spell make you a spellcaster?
- Is there any way to orbit around the object instead of a 3D cursor?
- How to handle missing value if imputation doesnt make sense
- Do roots of these polynomials approach the negative of the Euler-Mascheroni constant?
- What is pictured in this SHERLOC camera?
- Egypt - Duty free notation on passport
- Why does hooking voltmeter to two transformers show 0 voltage?
- MAGENTO 2: PHP Parse error: syntax error, unexpected 'MageSuite' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST) ... on line 7
- Which sentence is correct ? 我 对 欧洲 历史 很 熟悉 or 我 很 熟悉 欧洲 历史
- Why are trials on "Law & Order" in the New York Supreme Court?
- Why does Jesus turn to the Father to forgive in Luke 23:34?
- Why are physically impossible and logically impossible concepts considered separate in terms of probability?
- Did any DOS compatibility layers exist for any UNIX-like systems before DOS started to become outmoded?
- OK to delete Windows.db file on PC?
- Acidity of alcohols and basicity of amines
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

Solve real coding problems
C# – Deserialize JSON using different property names
When JSON property names and class property names are different, and you can’t just change the names to match, you have three options:
- Use the JsonPropertyName attribute.
- Use a naming policy (built-in or custom).
- A combination of these two. In other words, use JsonPropertyName for special cases that your naming policy doesn’t handle.
These affect both deserialization and serialization.
Let’s say you have the following JSON with camel-cased property names:
Note: The Newtonsoft equivalent is [JsonProperty(“title”)]
Alternatively, you can use a naming policy to change ALL property names:
Note: ASP.NET Core defaults to using JsonSerializerDefaults.Web , which includes JsonNamingPolicy.CamelCase .
Table of Contents
Custom naming policy
To create your own custom naming policy, subclass JsonNamingPolicy and override the ConvertName() method:
To use your custom naming policy, set it in JsonSerializerOptions:
Implementing ConvertName()
There are two main ways to implement this:
- Name mappings with a dictionary.
- Algorithmic name transformation.
If needed, do a hybrid approach. Start with a simple algorithm that works for most cases and use a dictionary (or apply the JsonPropertyName attribute) to handle your specific edge cases.
Here’s examples of these two approaches.
Example – Name mappings with a dictionary
Here’s a custom naming policy that hardcodes these name mappings in a dictionary:
This is a nice, flexible option. You can hardcode the mappings or load them in from a config file (or some other external source). Since this allows you to extend your classes without directly modifying them, it adheres to the Open-Closed Principle.
Example – Algorithmically converting to simple snake case
And you want to map these properties to the following class, which is using pascal casing:
Here’s a simple snake case naming policy:
Note: This was tested on the names shown in the JSON / class shown above.
Snake case naming policy
System.Text.Json doesn’t have built-in snake (ex: author_name ) or kebab casing (ex: author-name). It’s possible they’ll add these in the future. This is a problem if you need it right now and don’t want to use the JsonPropertyName attribute.
Let’s say you have the following JSON with snake casing:
Here are your options:
- Use Newtonsoft instead. It supports snake and kebab case.
- Write your own custom naming policy ( example shown above ).
- Use a third-party library, such as JorgeSerrano.Json.JsonSnakeCaseNamingPolicy.
System.Text.Json with a third-party snake case naming policy
First, install the JorgeSerrano.Json.JsonSnakeCaseNamingPolicy package:
Note: This is using the Package Manager in Visual Studio.
Now use it by setting it in the options:
This outputs the following:

Newtonsoft snake case naming strategy
To change the naming strategy in Newtonsoft, set ContractResolver.NamingStrategy in the settings. Here’s an example of using the snake case naming strategy:
Note: System.Text.Json uses “naming policy”, while Newtonsoft uses “naming strategy.”
Leave a Comment Cancel reply
- IoT – Temperature Monitor in Raspberry Pi using .NET Core
- Set up Raspberry Pi – Step by step
- IoT- Light Bulbs Controller Raspberry Pi using .NET Core
- Raspberry Pi in .NET Core with examples
- Build a .NET Core IoT App on Raspberry Pi
TheCodeBuzz
Best Practices for Software Development
JSON Change Name of field or Property for Serializing Deserializing
Json change name of field or property serialization.

In this tutorial, we shall see how to change the name of a field to map to another JSON property on serialization in C# or .NET Codebase.
We shall see how to use [ JsonPropertyName (“”)] attribute which helps to serialize or deserializing the property name that is present in the JSON This way you are able to override any naming policy available by default.
Today in this article, we will cover below aspects,
JsonPropertyName in NewtonSoft Vs System.Text.Json
Using jsonpropertynameattribute annotation.
You might find multiple needs to map a field to a different property while performing serialization or de-serialization.
JsonPropertyName attribute is available in both Newtonsoft.Json and System.Text.Json and provides the same ability to override the property name.
I have simple class Entity as shown below,
If this is serialized to JSON, below is the output we shall get,
NewtonSoft.JSON
System.Text.Json
JSON output
Using above both ways we get below JSON output,
Lets now customize the property field output.
Let’s say you want “First_Name” and “Last_Name” as the property field instead of the old ones.
In such case , please use JsonProperty attribute annotation as below,

The generated Entity would now look as below,
Please note that JsonPropertyNameAttribute is available for both JSON.NET(Newtonsoft) and System.Text.Json
As per Microsoft,
A property value enclosed in single quotes will result in a JsonException . System.Text.Json shall accept property names and string values only in double-quotes as per RFC 8259 specification.
References:
- System.Text.Json -Serialization and Deserialization in .NET
JsonPropertyNameAttribute helps you overriding the property name that is present in the JSON when serializing and deserializing in a simple way using attribute annotation.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to get a notification on freshly published best practices and guidelines for software design and development.
Growing by Sharing
Related Posts:
- MongoDB C# .NET - Change The Type of a field
- MongoDB Change The Type of a field in a Nested Array
- Change the root password in Windows 10 WSL
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
Notify and subscribe me when reply to comments are added.
Privacy Overview
This sample uses JsonPropertyAttribute to change the names of properties when they are serialized to JSON.


How to change property names when serializing with Json.net?
In Json.NET, you can change the property names during serialization by using the JsonPropertyAttribute on your class properties. Here is an example:
In this example, the JsonPropertyAttribute is used to specify that the property OldName should be serialized as "newName" . During serialization, the OldName property will be serialized as "newName" .
You can also specify additional serialization options for the property using the JsonPropertyAttribute . For example, you can specify whether the property should be required during deserialization or whether it should be omitted if it has a null value. Here is an example:
In this example, the JsonPropertyAttribute is used to specify that the property OldName should be serialized as "newName" and that it is required during deserialization. If the OldName property is null during serialization, an exception will be thrown.
You can also use the JsonProperty attribute on a class to specify the naming strategy for all properties in the class. For example:
In this example, the NamingStrategyType property of the JsonObject attribute is set to CamelCaseNamingStrategy , which will change the property name from "MyProperty" to "myProperty" during serialization. This strategy will be applied to all properties in the class, unless they are overridden with their own JsonPropertyAttribute .
More C# Questions
- Easier way to debug a Windows service in C#
- Custom numeric format string to always display the sign in C#
- Metadata file '.dll' could not be found in C#
- How to access named capturing groups in a .NET Regex?
- How to get the executing assembly version in C#?
- Converting from IEnumerable to List in C#
- DateTime "null" / uninitialized value in C#?
- How to add an item to a IEnumerable<T> collection in C#?
- Previous
- Next
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Json Property Name Attribute Class
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Specifies the property name that is present in the JSON when serializing and deserializing. This overrides any naming policy specified by JsonNamingPolicy .
For more information, see How to customize property names and values with System.Text.Json .
Constructors
Additional resources.

IMAGES
VIDEO
COMMENTS
I would like to change the property names to be something different (say, change 'foo' to 'bar'). In the Json.net documentation, under 'Serializing and Deserializing JSON' → 'Serialization Attributes' it says "JsonPropertyAttribute... allows the name to be customized". But there is no example.
By default, property names and dictionary keys are unchanged in the JSON output, including case. Enum values are represented as numbers. In this article, you'll learn how to: Customize individual property names Convert all property names to camel case Implement a custom property naming policy Convert dictionary keys to camel case
This is the final solution: 1) Created a custom Attribute and decorated the properties that I needed its name changed in the serialized Json: [AttributeUsage (AttributeTargets.Property)] class MyCustomJsonPropertyAttribute : Attribute { public string PropertyName { get; protected set; } public MyCustomJsonPropertyAttribute (string propertyName ...
Alternatively, you can use a naming policy to change ALL property names: using System.Text.Json; var options = new JsonSerializerOptions () { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; var codeBook = JsonSerializer.Deserialize<Book> (bookJson, options); Code language: C# (cs)
Using JsonPropertyNameAttribute annotation Lets now customize the property field output. Let’s say you want “First_Name” and “Last_Name” as the property field instead of the old ones. In such case , please use JsonProperty attribute annotation as below, The generated Entity would now look as below, 1 2 3 4 5 6 7 8 9 { "First_Name": "ABCD",
This sample uses JsonPropertyAttribute to change the names of properties when they are serialized to JSON. Sample Types Copy public class Videogame { [JsonProperty ( "name" )] public string Name { get; set; } [JsonProperty ( "release_date" )] public DateTime ReleaseDate { get; set; } } Usage Copy
In Json.NET, you can change the property names during serialization by using the JsonPropertyAttribute on your class properties. Here is an example: In this example, the JsonPropertyAttribute is used to specify that the property OldName should be serialized as "newName". During serialization, the OldName property will be serialized as "newName ...
For more information, see How to customize property names and values with System.Text.Json. Constructors Json Property Name Attribute (String) Initializes a new instance of JsonPropertyNameAttribute with the specified property name. Properties Methods Applies to