Recursive AI

Change a YAML property name with an attribute in C#

OneYaml is a free, open-source YAML library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

Put [YamlPropertyName("job-name")] on the property to use job-name in YAML.

Terminal
dotnet add package OneYaml

Targets .NET 8 and .NET 10 (example).

C#
using OneYaml;
 
var job = new Job("nightly");
var yaml = YamlSerializer.Serialize(job);
Console.Write(yaml);
 
record Job(
    [property: YamlPropertyName("job-name")]
    string Name);

Unzip the example, then dotnet run.

The snippet prints:

Text
job-name: nightly

If the input still uses name, it doesn’t bind to Name under this mapping. Unmapped keys are skipped by default.

Variations

Read the renamed key. Replace the code between using OneYaml; and the Job record:

C#
var job = YamlSerializer.Deserialize<Job>(
    "job-name: nightly\n")!;
Console.WriteLine(job.Name);
Text
nightly

The short answer

[YamlPropertyName("job-name")] makes job-name the YAML key for Name, both when you serialize the object and when you read it back. It changes the YAML key, not the C# member. This is useful when a config file already has a fixed spelling, such as a key with a hyphen that wouldn’t be valid in a C# identifier.

How do I change YAML property names in C#?

Use an attribute for an exception on one property and a naming policy for the convention shared by the other properties. OneYaml defaults to camel case. That means a property called JobName normally becomes jobName. With the attribute above, the key is job-name regardless of the policy. If a whole model should use names as declared, set YamlSerializerOptions.PropertyNamingPolicy to null; explicit names still take precedence. The serializer guide lists the naming options for reading and writing.

In a positional record, use the property: target as in the example. The attribute belongs to the property the compiler generates, not the constructor parameter. In a class with an explicitly declared property, put [YamlPropertyName("job-name")] immediately above the property without property:.

Can I use JsonPropertyName for YAML in C#?

Yes. OneYaml honors the System.Text.Json.Serialization.JsonPropertyName attribute when the same member has no YAML name attribute. Use that when both outputs should share a spelling. If the JSON and YAML contracts differ, keep the JSON attribute and add YamlPropertyName; OneYaml uses the YAML name for YAML. See serializer attributes.

OneYaml 1.2.1 doesn’t support aliases through [YamlPropertyName]: the attribute accepts one key, so it can’t bind both name and job-name to Name.

All oneyaml C# recipes