YAML 1.2
The ShapeShift.Yaml package maps PolyType contracts to YAML 1.2.
The reader accepts the YAML 1.2 syntax. The writer emits the same block style it always has, so existing documents stay stable.
Install the ShapeShift.Yaml package and annotate serialized root types with PolyType's GenerateShapeAttribute:
YamlSerializer serializer = new();
Person person = new("Ada", ["mathematics", "programming"]);
string yaml = serializer.Serialize(person);
Person? copy = serializer.Deserialize<Person>(yaml);
That sample writes:
Name: Ada
Interests:
- mathematics
- programming
YamlSerializer supports:
- Serialization to one YAML document, and deserialization of the first document in a stream.
DeserializeAllfor every document in a stream.- All shared ShapeShift converters and policies, including naming policies, generated surrogates, attributed unions, default-value omission, and strict duplicate/required-member validation.
- Trimmed and NativeAOT applications. The parser is part of this package and does not reflect.
Reading YAML 1.2
YamlDecoder composes the stream before the first token is read. It accepts:
- Block and flow sequences and mappings, including a block sequence nested directly under a key at that key's column.
- Plain, single-quoted, double-quoted, literal (
|), and folded (>) scalars, including chomping (+,-, and the default clip). - Anchors and aliases, including an alias used as a mapping key. Recursive aliases are rejected.
- Tags.
!!str,!!null,!!bool,!!int,!!float, and!!binaryselect the core type.!!float 1is a float. A bare!forces a string, so! 12and! truestay text. Other tags are preserved as text. %YAMLand%TAGdirectives, and---/...document markers.
Untagged plain scalars use the YAML 1.2 core schema:
null,Null,NULL,~, and an empty plain scalar are null.trueandfalse, in any case, are Booleans.yes,no,on, andoffstay strings.- Integers may be decimal,
0xhexadecimal, or0ooctal, and may be larger than 64 bits. - Floats require a decimal point or an exponent.
.nan,.inf, and-.infare the non-finite forms. - Quoted and block scalars stay strings unless a tag says otherwise. Timestamps stay strings, so
ReadDateTimeandReadTimeSpanstill parse text.
A mapping key may be any node. A scalar key is a property name; a collection key is a nested value.
After each document, NextTokenType is EndDocument. TryAdvanceDocument moves to the next document and returns false at the end of the stream. DocumentCount is zero for an empty or comment-only stream. A caller that reads one value from that stream still sees a null, which is what Deserialize returns. DeserializeAll returns an empty list.
YamlSerializer serializer = new();
IReadOnlyList<Note?> notes = serializer.DeserializeAll<Note>("Text: one\n---\nText: two\n");
Load options
YamlLoadOptions is immutable and lives on YamlSerializer.LoadOptions. The YamlDecoder constructor takes the same record.
AllowDuplicateKeysdefaults to false, so a repeated mapping key is an error. Keys are compared by their resolved value:1and0x1are the same key, and1and"1"are not. Set it to true to keep every entry in source order. For example, this document is rejected unless duplicates are allowed:name: Ada name: GraceMaxDepthdefaults to 256. Block scalars do not count. The same limit applies when an alias is expanded, so a chain of collections that each alias the previous one cannot nest deeper than the limit. Parsing recurses up to this depth.MaxAliasExpansionsdefaults to 4096. Each alias that is followed counts as one.MaxExpandedNodesdefaults to 1048576. The first read of a node is free. Each later read through an alias counts as one node, so a large anchored collection cannot be replayed without bound. A replayed string is the same string, not a copy.
YamlSerializer serializer = new()
{
LoadOptions = new YamlLoadOptions
{
AllowDuplicateKeys = true,
MaxDepth = 64,
MaxAliasExpansions = 1024,
MaxExpandedNodes = 100_000,
},
};
What the writer emits
The writer produces indented block mappings and sequences. It quotes scalars that would otherwise change meaning on the way back in, including nulls, Booleans, numbers, and strings that start with an indicator. It does not emit flow collections, anchors, aliases, tags, or directives. Binary values are rejected on write; !!binary is accepted on read.
Invalid input
The reader rejects a document that breaks YAML 1.2 structure: a bad indent, a tab used as block indentation, a directive with no document, an unknown tag handle, a recursive alias, or content after the document. Collection limits and duplicate-key checks throw DecoderException as well.