C#
JsonPropertyName
Learn to customize JSON key names with [JsonPropertyName].
Key names with JsonPropertyName
By default JsonSerializer uses the property name as-is: the Name property becomes the key "Name". The [JsonPropertyName] attribute lets you change this name.
Example: [JsonPropertyName("first_name")] public string Name { get; set; }. Now serialization uses the "first_name" key. This is useful when you want short or localized keys, or when you must match an existing data format. The attribute needs using System.Text.Json.Serialization;.
The Serialization namespace
The [JsonPropertyName] attribute lives in the System.Text.Json.Serialization namespace. Add using System.Text.Json.Serialization; to use it. This namespace holds all attributes that customize serialization behavior.
Other useful attributes: [JsonIgnore] excludes a property from serialization; [JsonConverter] binds a custom converter. These attributes go on the property declaration, right above the property.
Exercise Customize key names
In the Person class below, add [JsonPropertyName("ad")] to the Name property and [JsonPropertyName("yas")] to the Age property. Then in Main create an instance, serialize with JsonSerializer.Serialize and print.
Show example solution
Above Name add [JsonPropertyName("ad")], above Age add [JsonPropertyName("yas")]. In Main add string text = JsonSerializer.Serialize(p); Console.WriteLine(text);.
Example solution:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
class Person
{
[JsonPropertyName("ad")]
public string Name { get; set; }
[JsonPropertyName("yas")]
public int Age { get; set; }
}
class Program
{
static void Main()
{
var p = new Person { Name = "Alex", Age = 30 };
string text = JsonSerializer.Serialize(p);
Console.WriteLine(text);
}
}
Test yourself
-
Match the attribute to its output
- [JsonPropertyName("ad")]
- "ad":"Alex"
- [JsonPropertyName("yas")]
- "yas":30
- (no attribute)
- "Name":"Alex"
- [JsonPropertyName("id")]
- "id":1
-
Complete the attribute
[____("first_name")]
public string Name { get; set; }
Show answer
[JsonPropertyName("first_name")]
public string Name { get; set; }
-
What does JsonPropertyName do?
- Excludes the property from serialization
- Changes the property's key name
- Changes the property's type
- Hides the property
Show answer
Hides the property — Correct. JsonPropertyName changes the property's key name in the text.
Next lesson: JsonSerializerOptions