• 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 ?

Yván Ecarri's user avatar

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 .

Hot Network Questions

change property name json c#

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 .

MAKOLYTE

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:

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:

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:

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

TheCodeBuzz

Best Practices for Software Development

JSON Change Name of field or Property for Serializing Deserializing

Json change name of field or property serialization.

JSON Property name system text json

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,

JSON Property name system text json vs newtonsoft

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:

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:

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.

change property name json c#

change property name json c#

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

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

  1. Json Converter C# Ignore Property

    change property name json c#

  2. c#

    change property name json c#

  3. Json Property Name With Dot

    change property name json c#

  4. c#

    change property name json c#

  5. Json Property Name With Dot

    change property name json c#

  6. c#

    change property name json c#

VIDEO

  1. How to JSON data work in asp.net with C# using web service

  2. HTML and CSS Animation

  3. 88 Oceano Street, Copacabana

  4. 6 Vista Avenue, Copacabana

  5. 7 Fiesta Crescent, Copacabana

  6. 52 Del Monte Place, Copacabana

COMMENTS

  1. c# - How can I change property names when serializing with ...

    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.

  2. How to customize property names and values with System.Text.Json

    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

  3. c# - How to change property names when serializing to Json in ...

    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 ...

  4. C# – Deserialize JSON using different property names

    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)

  5. JSON Change Name of field or Property when serializing, de ...

    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",

  6. JsonPropertyAttribute name - Newtonsoft

    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

  7. 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 ...

  8. JsonPropertyNameAttribute Class (System.Text.Json ...

    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