Skip to main content

How to Rename a JSON Property with JsonPropertyName in C#

· 7 min read
Jagdish Kumawat
Founder @ Dewiride

Put [JsonPropertyName("cook_time")] on a property, and System.Text.Json uses the name cook_time for it in the JSON, both when it writes the JSON and when it reads it. Your C# code keeps the property's own name.

Microsoft's reference for the attribute: Specifies the property name that is present in the JSON when serializing and deserializing.

Without it, the JSON uses the C# names. The System.Text.Json guide: By default, property names and dictionary keys are unchanged in the JSON output, including case. That's a problem when the JSON belongs to someone else, such as a website whose names are lower case with underscores. The same guide: To set the name of individual properties, use the [JsonPropertyName] attribute.

Syntax​

Syntax
using System.Text.Json.Serialization;

class <Class>
{
[JsonPropertyName("<jsonName>")]
public <Type> <Property> { get; set; }
}
PartWhat it is
using System.Text.Json.Serialization;The namespace the attribute is in
[JsonPropertyName("<jsonName>")]The attribute, on the line above the property it renames
<jsonName>The name in the JSON. The constructor's reference: Initializes a new instance of JsonPropertyNameAttribute with the specified property name.
<Type> <Property>The C# property. Your C# code still uses <Property>

The attribute goes on a property or a field. On a positional record's parameter, write [property: JsonPropertyName("<jsonName>")]. The records reference, whose own example uses this attribute: The property: target indicates that the attribute is applied to the compiler-generated property.

The Example​

A console app called JsonPropertyNames has a Recipe class for recipes from a website whose JSON names the cooking time cook_time and the number of servings serves. It writes a recipe as JSON, then reads one back.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n JsonPropertyNames
cd JsonPropertyNames
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/JsonPropertyNames/JsonPropertyNames.csproj:
Determining projects to restore...
Restored /Users/you/source/JsonPropertyNames/JsonPropertyNames.csproj (in 46 ms).
Restore succeeded.

dotnet new console -n JsonPropertyNames creates a folder named JsonPropertyNames with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or JsonPropertyNames.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. The class goes at the end of the file:

Program.cs (the class)
class Recipe
{
public string Name { get; set; } = "";

[JsonPropertyName("cook_time")]
public int CookingMinutes { get; set; }

[JsonPropertyName("serves")]
public int Servings { get; set; }
}

Name has no attribute, so the JSON uses its C# name. CookingMinutes gets the JSON name cook_time, and Servings gets serves. = "" starts Name as an empty string instead of null.

At the top of the file, the using lines and a recipe to write as JSON:

Program.cs (write the JSON)
using System.Text.Json;
using System.Text.Json.Serialization;

// A recipe with C# property names. Two of them get their own names in the JSON.
Recipe soup = new() { Name = "Tomato soup", CookingMinutes = 30, Servings = 4 };

// Serialize: cook_time and serves replace the C# names. Name keeps its own.
string json = JsonSerializer.Serialize(soup);
Console.WriteLine(json);

System.Text.Json holds JsonSerializer, and System.Text.Json.Serialization holds the attribute. JsonSerializer.Serialize(soup) turns the object into a JSON string.

Then JSON with the website's names, read into a Recipe:

Program.cs (read the JSON)
// Deserialize: the same JSON names fill the properties.
string fromWebsite = """{"Name":"Pancakes","cook_time":15,"serves":2}""";
Recipe pancakes = JsonSerializer.Deserialize<Recipe>(fromWebsite)!;
Console.WriteLine($"{pancakes.Name}: {pancakes.CookingMinutes} minutes, serves {pancakes.Servings}");

fromWebsite is a raw string literal: everything between the two """ is text, so the quotes inside need no escaping. JsonSerializer.Deserialize<Recipe> reads it into a new Recipe, and the ! tells the compiler the result isn't null.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
{"Name":"Tomato soup","cook_time":30,"serves":4}
Pancakes: 15 minutes, serves 2

macOS-style terminal window titled Terminal — JsonPropertyNames showing dotnet run printing the JSON with Name Tomato soup, cook_time 30 and serves 4, then Pancakes: 15 minutes, serves 2

  • Writing: the JSON has cook_time and serves where the C# names are CookingMinutes and Servings. Name kept its C# name.
  • Reading: the website's cook_time and serves filled CookingMinutes and Servings: 15 minutes, serves 2.

The guide sums it up: the name set by the attribute Applies in both directions, for serialization and deserialization.

The Complete File​

macOS-style code window titled Program.cs — JsonPropertyNames showing a Recipe written as JSON with JsonSerializer.Serialize, JSON with cook_time and serves read back with JsonSerializer.Deserialize, and the Recipe class whose CookingMinutes and Servings properties carry JsonPropertyName attributes with the names cook_time and serves

Program.cs
using System.Text.Json;
using System.Text.Json.Serialization;

// A recipe with C# property names. Two of them get their own names in the JSON.
Recipe soup = new() { Name = "Tomato soup", CookingMinutes = 30, Servings = 4 };

// Serialize: cook_time and serves replace the C# names. Name keeps its own.
string json = JsonSerializer.Serialize(soup);
Console.WriteLine(json);

// Deserialize: the same JSON names fill the properties.
string fromWebsite = """{"Name":"Pancakes","cook_time":15,"serves":2}""";
Recipe pancakes = JsonSerializer.Deserialize<Recipe>(fromWebsite)!;
Console.WriteLine($"{pancakes.Name}: {pancakes.CookingMinutes} minutes, serves {pancakes.Servings}");

class Recipe
{
public string Name { get; set; } = "";

[JsonPropertyName("cook_time")]
public int CookingMinutes { get; set; }

[JsonPropertyName("serves")]
public int Servings { get; set; }
}

Common Mistakes​

MistakeWhat happensDo this instead
Reading JSON that still uses the C# namesJSON with "CookingMinutes":15 and "Servings":2 gave CookingMinutes: 0, Servings: 0: the properties now answer to their JSON names onlyUse the names from the attributes, cook_time and serves
Expecting the names to match in any case"COOK_TIME" and "Serves" left both properties at 0. The guide: By default, deserialization looks for case-sensitive property name matches between JSON and the target object properties.Set PropertyNameCaseInsensitive = true in a JsonSerializerOptions: the same JSON gave 15 minutes, serves 2
[JsonPropertyName("cook_time")] on a positional record's parameter, without a targeterror CS0592: Attribute 'JsonPropertyName' is not valid on this declaration type. It is only valid on 'property, indexer, field' declarations.Write [property: JsonPropertyName("cook_time")]: the record wrote "cook_time":30 and read it back
Giving two properties the same JSON nameInvalidOperationException: The JSON property name for 'Recipe.time' collides with another property.Give each property a name of its own

FAQ​

Does a naming policy change a name set with JsonPropertyName?​

No. With PropertyNamingPolicy = JsonNamingPolicy.CamelCase, Name became name, but cook_time and serves stayed as they were: {"name":"Tomato soup","cook_time":30,"serves":4}. JsonNamingPolicy.KebabCaseUpper turned Name into NAME and left them again. The attribute's reference: The specified property name overrides any naming policy specified by JsonNamingPolicy.

Can a naming policy rename every property instead?​

Yes, when the JSON names follow one rule. JsonNamingPolicy.SnakeCaseLower, the naming policy for lowercase snake-casing, turned a class with no attributes into {"name":"Tomato soup","cooking_minutes":30,"servings":4}. A policy writes each C# name in another style, so CookingMinutes became cooking_minutes, not a different word such as cook_time. For a different word, use JsonPropertyName.

Conclusion​

[JsonPropertyName("<jsonName>")] gives one property its own name in the JSON, for writing and for reading, and it wins over any naming policy. Read JSON with exactly that name, or set PropertyNameCaseInsensitive when the case differs, give each property a name of its own, and on a positional record write property: in front of the attribute.

Additional Resources​