### OK Indentation Example Source: https://github.com/aaubry/yamldotnet/blob/master/CONTRIBUTING.md Demonstrates acceptable line breaking for readability in C#. ```C# Traverse( new ObjectDescriptor( value.Value, underlyingType, value.Type, value.ScalarStyle ), visitor, currentDepth ); ``` -------------------------------- ### Build the Project with .NET CLI Source: https://github.com/aaubry/yamldotnet/blob/master/CONTRIBUTING.md Use the standard .NET CLI to build the project. Ensure the .NET Core 3.1 SDK or later is installed. ```bash dotnet build ``` -------------------------------- ### Install YamlDotNet.Signed NuGet Package Source: https://github.com/aaubry/yamldotnet/wiki/Home Use this command in the Package Manager Console to install the signed version of the YamlDotNet NuGet package if signed assemblies are required. ```powershell PM> Install-Package YamlDotNet.Signed ``` -------------------------------- ### Alternative OK Indentation Example Source: https://github.com/aaubry/yamldotnet/blob/master/CONTRIBUTING.md Shows another valid way to break lines for C# code, prioritizing conciseness when appropriate. ```C# Traverse( new ObjectDescriptor(value.Value, underlyingType, value.Type, value.ScalarStyle), visitor, currentDepth ); ``` -------------------------------- ### Install YamlDotNet via NuGet Package Manager Source: https://github.com/aaubry/yamldotnet/blob/master/README.md Installs the YamlDotNet library into your .NET project using the NuGet Package Manager console. ```powershell PM> Install-Package YamlDotNet ``` -------------------------------- ### Not Very Good Indentation Example Source: https://github.com/aaubry/yamldotnet/blob/master/CONTRIBUTING.md Illustrates an indentation style that is discouraged in C# for readability. ```C# Traverse(new ObjectDescriptor(value.Value, underlyingType, value.Type, value.ScalarStyle), visitor, currentDepth); ``` -------------------------------- ### Awful Indentation Example Source: https://github.com/aaubry/yamldotnet/blob/master/CONTRIBUTING.md Highlights an extremely discouraged indentation style in C# that harms readability. ```C# Traverse(new ObjectDescriptor(value.Value, underlyingType, value.Type, value.ScalarStyle), visitor, currentDepth); ``` -------------------------------- ### Example Color Property Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.TypeConverters A C# property of type System.Drawing.Color that requires custom serialization. ```csharp public System.Drawing.Color color { get; set; } = Color.Green; ``` -------------------------------- ### Custom Object Factory for Dependency Injection Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Deserializer Implement `IObjectFactory` to create custom instances of types during deserialization, especially when constructors require dependency injection. This example shows how to create an `OrderItem` with a `TenPercentDiscountCalculationPolicy`. ```csharp interface IDiscountCalculationPolicy { decimal Apply(decimal basePrice); } class TenPercentDiscountCalculationPolicy : IDiscountCalculationPolicy { public decimal Apply(decimal basePrice) { return basePrice - basePrice / 10m; } } class OrderItem { private readonly IDiscountCalculationPolicy discountPolicy; public OrderItem(IDiscountCalculationPolicy discountPolicy) { this.discountPolicy = discountPolicy; } public string Description { get; set; } public decimal BasePrice { get; set; } public decimal FinalPrice => discountPolicy.Apply(BasePrice); } ``` ```csharp class OrderItemFactory : IObjectFactory { private readonly IObjectFactory fallback; public OrderItemFactory(IObjectFactory fallback) { this.fallback = fallback; } public object Create(Type type) { if (type == typeof(OrderItem)) { return new OrderItem(new TenPercentDiscountCalculationPolicy()); } else { return fallback.Create(type); } } } ``` ```yaml Description: High Heeled "Ruby" Slippers BasePrice: 100.27 ``` ```csharp var deserializer = new DeserializerBuilder() .WithObjectFactory(new OrderItemFactory(new DefaultObjectFactory())) .Build(); var orderItem = deserializer.Deserialize(yamlInput); Console.WriteLine($"Final price: {orderItem.FinalPrice}"); ``` -------------------------------- ### Deserialize YAML to C# Object Graph Source: https://github.com/aaubry/yamldotnet/wiki/Samples.DeserializeObjectGraph This snippet shows the core process of deserializing a YAML string into a C# object graph. It configures the deserializer with camel case naming and then deserializes the 'Order' object. The example includes the necessary C# classes and the YAML document as a string. ```C# using System; using System.Collections.Generic; using System.IO; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Samples.Helpers; using Xunit.Abstractions; namespace YamlDotNet.Samples { public class DeserializeObjectGraph { private readonly ITestOutputHelper output; public DeserializeObjectGraph(ITestOutputHelper output) { this.output = output; } [Sample( DisplayName = "Deserializing an object graph", Description = "Shows how to convert a YAML document to an object graph." )] public void Main() { var input = new StringReader(Document); var deserializer = new DeserializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .Build(); var order = deserializer.Deserialize(input); output.WriteLine("Order"); output.WriteLine("-----"); output.WriteLine(); foreach (var item in order.Items) { output.WriteLine("{0}\t{1}\t{2}\t{3}", item.PartNo, item.Quantity, item.Price, item.Descrip); } output.WriteLine(); output.WriteLine("Shipping"); output.WriteLine("--------"); output.WriteLine(); output.WriteLine(order.ShipTo.Street); output.WriteLine(order.ShipTo.City); output.WriteLine(order.ShipTo.State); output.WriteLine(); output.WriteLine("Billing"); output.WriteLine("-------"); output.WriteLine(); if (order.BillTo == order.ShipTo) { output.WriteLine("*same as shipping address*"); } else { output.WriteLine(order.ShipTo.Street); output.WriteLine(order.ShipTo.City); output.WriteLine(order.ShipTo.State); } output.WriteLine(); output.WriteLine("Delivery instructions"); output.WriteLine("---------------------"); output.WriteLine(); output.WriteLine(order.SpecialDelivery); } public class Order { public string Receipt { get; set; } public DateTime Date { get; set; } public Customer Customer { get; set; } public List Items { get; set; } [YamlMember(Alias = "bill-to", ApplyNamingConventions = false)] public Address BillTo { get; set; } [YamlMember(Alias = "ship-to", ApplyNamingConventions = false)] public Address ShipTo { get; set; } public string SpecialDelivery { get; set; } } public class Customer { public string Given { get; set; } public string Family { get; set; } } public class OrderItem { [YamlMember(Alias = "part_no", ApplyNamingConventions = false)] public string PartNo { get; set; } public string Descrip { get; set; } public decimal Price { get; set; } public int Quantity { get; set; } } public class Address { public string Street { get; set; } public string City { get; set; } public string State { get; set; } } private const string Document = @"--- receipt: Oz-Ware Purchase Invoice date: 2007-08-06 customer: given: Dorothy family: Gale items: - part_no: A4786 descrip: Water Bucket (Filled) price: 1.47 quantity: 4 - part_no: E1628 descrip: High Heeled ""Ruby"" Slippers price: 100.27 quantity: 1 bill-to: &id001 street: |- 123 Tornado Alley Suite 16 city: East Westville state: KS ship-to: *id001 specialDelivery: > Follow the Yellow Brick Road to the Emerald City. Pay no attention to the man behind the curtain. ..."; } } ``` -------------------------------- ### Custom Integer Sequence Flow Style Emitter Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Serializer Registers a custom IEventEmitter to force flow style for sequences of integers. This example demonstrates how to intercept and modify YAML events during serialization. ```csharp class FlowStyleIntegerSequences : ChainedEventEmitter { public FlowStyleIntegerSequences(IEventEmitter nextEmitter) : base(nextEmitter) {} public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { if (typeof(IEnumerable).IsAssignableFrom(eventInfo.Source.Type)) { eventInfo = new SequenceStartEventInfo(eventInfo.Source) { Style = SequenceStyle.Flow }; } nextEmitter.Emit(eventInfo, emitter); } } ``` ```csharp var serializer = new SerializerBuilder() .WithEventEmitter(next => new FlowStyleIntegerSequences(next)) .Build(); serializer.Serialize(Console.Out, new { strings = new[] { "one", "two", "three" }, ints = new[] { 1, 2, 3 } }); ``` -------------------------------- ### Configure Deserializer with Custom Node Deserializer Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Deserializer Configure the DeserializerBuilder to use a custom INodeDeserializer, such as ValidatingNodeDeserializer, to enhance built-in deserialization. This example replaces the default ObjectNodeDeserializer. ```csharp var deserializer = new DeserializerBuilder() .WithNodeDeserializer( inner => new ValidatingNodeDeserializer(inner), s => s.InsteadOf() ) .Build(); try { deserializer.Deserialize(yamlInput); } catch(YamlException ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.InnerException.Message); } ``` -------------------------------- ### Deserializer Configuration with Validation Source: https://github.com/aaubry/yamldotnet/wiki/Samples.ValidatingDuringDeserialization Configures a YamlDotNet Deserializer to use the custom ValidatingNodeDeserializer, replacing the default ObjectNodeDeserializer. This setup ensures that all objects deserialized will undergo the validation process defined in ValidatingNodeDeserializer. ```C# var deserializer = new DeserializerBuilder() .WithNodeDeserializer(inner => new ValidatingNodeDeserializer(inner), s => s.InsteadOf()) .Build(); // This will fail with a validation exception var ex = Assert.Throws(() => deserializer.Deserialize(new StringReader(@"Name: ~")) ); Assert.IsType(ex.InnerException); ``` -------------------------------- ### Run Unit Tests with .NET CLI Source: https://github.com/aaubry/yamldotnet/blob/master/CONTRIBUTING.md Execute the project's unit tests using the .NET CLI. ```bash dotnet test ``` -------------------------------- ### Initialize Git Submodules Source: https://github.com/aaubry/yamldotnet/blob/master/CONTRIBUTING.md Before building, ensure all Git submodules are initialized and updated. ```bash git submodule update --init ``` -------------------------------- ### Basic Object Serialization Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Serializer Demonstrates the simplest way to serialize an object to YAML using the default Serializer settings. This is suitable for basic use cases. ```csharp var serializer = new YamlDotNet.Serialization.Serializer(); serializer.Serialize(Console.Out, new { Hello = "world" }); ``` -------------------------------- ### Execute Build Tool Targets Source: https://github.com/aaubry/yamldotnet/blob/master/CONTRIBUTING.md The build tool located in '/tools/build' orchestrates various automation tasks. Execute it with a specific target, such as 'Pack', 'Publish', or 'Release'. ```bash build.cmd ``` -------------------------------- ### Run Build Targets Source: https://github.com/aaubry/yamldotnet/wiki/BuildAndRelease Execute the build project without arguments to obtain usage information and a list of available targets. This command is used to understand the build system's capabilities. ```sh dotnet run ``` -------------------------------- ### Configure Serializer with Custom Converter Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.TypeConverters Builds a YamlDotNet serializer and registers the custom ColorConverter instance. ```csharp var serializer = new SerializerBuilder() .WithTypeConverter(ColorConverter.Instance) .Build(); string yaml = serializer.Serialize(components); testOutputHelper.WriteLine(yaml); ``` -------------------------------- ### ReadYaml Method for Color Deserialization Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.TypeConverters Deserializes a YAML mapping of R, G, and B components back into a System.Drawing.Color object. ```csharp public object ReadYaml(IParser parser, Type type) { parser.Consume(); parser.Consume(); byte r = byte.Parse(parser.Consume().Value); parser.Consume(); byte g = byte.Parse(parser.Consume().Value); parser.Consume(); byte b = byte.Parse(parser.Consume().Value); parser.Consume(); return Color.FromArgb(r, g, b); ;} ``` -------------------------------- ### WriteYaml Method for Color Serialization Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.TypeConverters Serializes a System.Drawing.Color object into a YAML mapping of its R, G, and B components. ```csharp public void WriteYaml(IEmitter emitter, object? value, Type type) { emitter.Emit(new MappingStart()); Color color = (Color)value!; emitter.Emit(new Scalar(nameof(color.R))); emitter.Emit(new Scalar(color.R.ToString())); emitter.Emit(new Scalar(nameof(color.G))); emitter.Emit(new Scalar(color.G.ToString())); emitter.Emit(new Scalar(nameof(color.B))); emitter.Emit(new Scalar(color.B.ToString())); emitter.Emit(new MappingEnd()); } ``` -------------------------------- ### Serialize with DynamicTypeResolver (Default) Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Serializer Illustrates the default serialization behavior using DynamicTypeResolver, which emits all members of the actual object type. This is useful when you want to preserve all details of the concrete object. ```csharp interface IContact { string Name { get; } string PhoneNumber { get; } } class CompanyContact : IContact { public string Name { get; set; } public string PhoneNumber { get; set; } public string RepresentativeName { get; set; } } IContact[] contacts = new IContact[] { new CompanyContact { Name = "Oz-Ware", PhoneNumber = "123456789", RepresentativeName = "John Smith" } }; var serializer = new SerializerBuilder() .Build(); serializer.Serialize(Console.Out, contacts); ``` -------------------------------- ### Create Object Graph in C# Source: https://github.com/aaubry/yamldotnet/wiki/Serialization This C# code demonstrates how to create a complex object graph, including nested objects and arrays, which can then be serialized into a YAML document. It defines classes for Address, Receipt, Customer, and Item. ```csharp var address = new Address { street = "123 Tornado Alley\nSuite 16", city = "East Westville", state = "KS" }; var receipt = new Receipt { receipt = "Oz-Ware Purchase Invoice", date = new DateTime(2007, 8, 6), customer = new Customer { given = "Dorothy", family = "Gale" }, items = new Item[] { new Item { part_no = "A4786", descrip = "Water Bucket (Filled)", price = 1.47M, quantity = 4 }, new Item { part_no = "E1628", descrip = "High Heeled \"Ruby\" Slippers", price = 100.27M, quantity = 1 } }, bill_to = address, ship_to = address, specialDelivery = "Follow the Yellow Brick\n" + "Road to the Emerald City.\n" + "Pay no attention to the\n" + "man behind the curtain." }; ``` -------------------------------- ### Configure Deserializer with Naming Convention Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Deserializer Configure a DeserializerBuilder to use a specific naming convention, like CamelCase, for mapping YAML keys to .NET member names. Build the deserializer after configuration. ```csharp var deserializer = new DeserializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .Build(); ``` -------------------------------- ### Serialize with Tag Mapping for Custom Type Identification Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Serializer Shows how to associate a custom YAML tag with a .NET type using WithTagMapping. This allows for explicit type identification in the YAML output, useful for distinguishing between different implementations of an interface. ```csharp interface IContact { string Name { get; } string PhoneNumber { get; } } class CompanyContact : IContact { public string Name { get; set; } public string PhoneNumber { get; set; } public string RepresentativeName { get; set; } } IContact[] contacts = new IContact[] { new CompanyContact { Name = "Oz-Ware", PhoneNumber = "123456789", RepresentativeName = "John Smith" } }; var serializer = new SerializerBuilder() .WithTagMapping("!company", typeof(CompanyContact)) .Build(); serializer.Serialize(Console.Out, contacts); ``` -------------------------------- ### Basic Object Deserialization Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Deserializer Use the default Deserializer to deserialize a simple YAML string into a dictionary. This is suitable for basic use cases. ```csharp var deserializer = new YamlDotNet.Serialization.Deserializer(); var dict = deserializer.Deserialize>("hello: world"); Console.WriteLine(dict["hello"]); ``` -------------------------------- ### Load and Examine YAML Stream Source: https://github.com/aaubry/yamldotnet/wiki/Samples.LoadingAYamlStream This C# snippet shows how to load a YAML string into YamlStream, access its documents and nodes, and iterate through mappings and sequences. It requires the YamlDotNet library. ```C# using System.IO; using YamlDotNet.RepresentationModel; using YamlDotNet.Samples.Helpers; using Xunit.Abstractions; namespace YamlDotNet.Samples { public class LoadingAYamlStream { private readonly ITestOutputHelper output; public LoadingAYamlStream(ITestOutputHelper output) { this.output = output; } [Sample( DisplayName = "Loading a YAML Stream", Description = "Explains how to load YAML using the representation model." )] public void Main() { // Setup the input var input = new StringReader(Document); // Load the stream var yaml = new YamlStream(); yaml.Load(input); // Examine the stream var mapping = (YamlMappingNode)yaml.Documents[0].RootNode; foreach (var entry in mapping.Children) { output.WriteLine(((YamlScalarNode)entry.Key).Value); } // List all the items var items = (YamlSequenceNode)mapping.Children[new YamlScalarNode("items")]; foreach (YamlMappingNode item in items) { output.WriteLine( "{0}\t{1}", item.Children[new YamlScalarNode("part_no")], item.Children[new YamlScalarNode("descrip")] ); } } private const string Document = @"--- receipt: Oz-Ware Purchase Invoice date: 2007-08-06 customer: given: Dorothy family: Gale items: - part_no: A4786 descrip: Water Bucket (Filled) price: 1.47 quantity: 4 - part_no: E1628 descrip: High Heeled "Ruby" Slippers price: 100.27 quantity: 1 bill-to: &id001 street: | 123 Tornado Alley Suite 16 city: East Westville state: KS ship-to: *id001 specialDelivery: >\n Follow the Yellow Brick Road to the Emerald City. Pay no attention to the man behind the curtain. ..."; } } ``` -------------------------------- ### Serialize with StaticTypeResolver Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Serializer Demonstrates serialization using StaticTypeResolver, which only emits members defined in the declared interface or base type. This is useful for enforcing a specific contract and hiding implementation details. ```csharp interface IContact { string Name { get; } string PhoneNumber { get; } } class CompanyContact : IContact { public string Name { get; set; } public string PhoneNumber { get; set; } public string RepresentativeName { get; set; } } IContact[] contacts = new IContact[] { new CompanyContact { Name = "Oz-Ware", PhoneNumber = "123456789", RepresentativeName = "John Smith" } }; var serializer = new SerializerBuilder() .WithTypeResolver(new StaticTypeResolver()) .Build(); serializer.Serialize(Console.Out, contacts); ``` -------------------------------- ### Accepts Method for Color Type Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.TypeConverters Implements the Accepts method to specify that this converter handles System.Drawing.Color types. ```csharp public bool Accepts(Type type) { return type == typeof(System.Drawing.Color); } ``` -------------------------------- ### Deserialize YAML to Object Without Type Information Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Deserializer Demonstrates deserializing YAML to a generic 'object' type when the concrete type is not known. This results in deserialization into dictionaries. ```csharp var deserializer = new DeserializerBuilder() .Build(); var contacts = deserializer.Deserialize(yamlInput); foreach (var contact in (IEnumerable)contacts) { Console.WriteLine(contact.GetType().FullName); } ``` -------------------------------- ### Emit JSON-Compatible YAML Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Serializer Use `JsonCompatible()` to ensure the generated YAML adheres strictly to JSON syntax. This is useful when interoperability with JSON parsers is required, as it limits the YAML constructs to those also present in JSON. ```csharp var serializer = new SerializerBuilder() .JsonCompatible() .Build(); serializer.Serialize(Console.Out, contacts); ``` -------------------------------- ### Configure Serializer with CamelCase Naming Convention Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Serializer Shows how to configure the SerializerBuilder to use a camelCase naming convention for YAML keys. This is useful for aligning with JavaScript or other systems that prefer camelCase. ```csharp var serializer = new SerializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .Build(); ``` -------------------------------- ### Implement SystemTypeFromTagNodeTypeResolver Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Deserializer Implement INodeTypeResolver to map YAML tags to .NET types. This resolver handles tags prefixed with '!clr:' to dynamically load types. ```csharp public class SystemTypeFromTagNodeTypeResolver : INodeTypeResolver { public bool Resolve(NodeEvent nodeEvent, ref Type currentType) { if (nodeEvent.Tag.StartsWith("!clr:")) { var netTypeName = nodeEvent.Tag.Substring(5); var type = Type.GetType(netTypeName); if (type != null) { currentType = type; return true; } } return false; } } ``` -------------------------------- ### Serialize Object to YAML String Source: https://github.com/aaubry/yamldotnet/blob/master/README.md Serializes a .NET object into a YAML formatted string using YamlDotNet. Requires the YamlDotNet.Serialization namespace and a naming convention. ```csharp using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; ... var person = new Person { Name = "Abe Lincoln", Age = 25, HeightInInches = 6f + 4f / 12f, Addresses = new Dictionary{ { "home", new Address() { Street = "2720 Sundown Lane", City = "Kentucketsville", State = "Calousiyorkida", Zip = "99978", }}, { "work", new Address() { Street = "1600 Pennsylvania Avenue NW", City = "Washington", State = "District of Columbia", Zip = "20500", }}, } }; var serializer = new SerializerBuilder() .WithNamingConvention(CamelCaseNamingConvention.Instance) .Build(); var yaml = serializer.Serialize(person); System.Console.WriteLine(yaml); // Output: // name: Abe Lincoln // age: 25 // heightInInches: 6.3333334922790527 // addresses: // home: // street: 2720 Sundown Lane // city: Kentucketsville // state: Calousiyorkida // zip: 99978 // work: // street: 1600 Pennsylvania Avenue NW // city: Washington // state: District of Columbia // zip: 20500 ``` -------------------------------- ### Basic ColorConverter Structure Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.TypeConverters The basic structure of a custom type converter implementing IYamlTypeConverter for System.Drawing.Color. ```csharp public class ColorConverter : IYamlTypeConverter { public static readonly IYamlTypeConverter Instance = new ColorConverter(); public bool Accepts(Type type) { // Can the converter handle this type? } public object? ReadYaml(IParser parser, Type type) { // Convert from text to an object during deserialization. } public void WriteYaml(IEmitter emitter, object? value, Type type) { // Convert from an object to text during serialization. } } ``` -------------------------------- ### Serialized YAML Output Source: https://github.com/aaubry/yamldotnet/wiki/Serialization This is the YAML representation of the C# object graph shown previously. It includes nested structures, arrays, and demonstrates YAML's block scalar styles for multi-line strings and anchors for reusable data. ```yaml receipt: Oz-Ware Purchase Invoice date: 2007-08-06T00:00:00.0000000 customer: given: Dorothy family: Gale items: - part_no: A4786 descrip: Water Bucket (Filled) price: 1.47 quantity: 4 - part_no: E1628 descrip: High Heeled "Ruby" Slippers price: 100.27 quantity: 1 bill_to: &address street: >- 123 Tornado Alley Suite 16 city: East Westville state: KS ship_to: *address specialDelivery: >- Follow the Yellow Brick Road to the Emerald City. Pay no attention to the man behind the curtain. ``` -------------------------------- ### C# Object Graph Serialization Source: https://github.com/aaubry/yamldotnet/wiki/Samples.SerializeObjectGraph Serializes a C# object graph to YAML. Ensure the YamlDotNet library is included in your project. The `SerializerBuilder().Build()` creates the serializer instance. ```C# using System; using YamlDotNet.Serialization; using YamlDotNet.Samples.Helpers; using Xunit.Abstractions; namespace YamlDotNet.Samples { public class SerializeObjectGraph { private readonly ITestOutputHelper output; public SerializeObjectGraph(ITestOutputHelper output) { this.output = output; } [Sample( DisplayName = "Serializing an object graph", Description = "Shows how to convert an object to its YAML representation." )] public void Main() { var address = new Address { street = "123 Tornado Alley\nSuite 16", city = "East Westville", state = "KS" }; var receipt = new Receipt { receipt = "Oz-Ware Purchase Invoice", date = new DateTime(2007, 8, 6), customer = new Customer { given = "Dorothy", family = "Gale" }, items = new Item[] { new Item { part_no = "A4786", descrip = "Water Bucket (Filled)", price = 1.47M, quantity = 4 }, new Item { part_no = "E1628", descrip = "High Heeled \"Ruby\" Slippers", price = 100.27M, quantity = 1 } }, bill_to = address, ship_to = address, specialDelivery = "Follow the Yellow Brick\n" + "Road to the Emerald City.\n" + "Pay no attention to the\n" + "man behind the curtain." }; var serializer = new SerializerBuilder().Build(); var yaml = serializer.Serialize(receipt); output.WriteLine(yaml); } } public class Address { public string street { get; set; } public string city { get; set; } public string state { get; set; } } public class Receipt { public string receipt { get; set; } public DateTime date { get; set; } public Customer customer { get; set; } public Item[] items { get; set; } public Address bill_to { get; set; } public Address ship_to { get; set; } public string specialDelivery { get; set; } } public class Customer { public string given { get; set; } public string family { get; set; } } public class Item { public string part_no { get; set; } public string descrip { get; set; } public decimal price { get; set; } public int quantity { get; set; } } } ``` -------------------------------- ### Convert YAML to JSON Source: https://github.com/aaubry/yamldotnet/wiki/Samples.ConvertYamlToJson Use this snippet to deserialize a YAML string into an object and then serialize it into a JSON string. Ensure YamlDotNet is included in your project. ```C# using System.IO; using YamlDotNet.Serialization; using YamlDotNet.Samples.Helpers; using Xunit.Abstractions; namespace YamlDotNet.Samples { public class ConvertYamlToJson { private readonly ITestOutputHelper output; public ConvertYamlToJson(ITestOutputHelper output) { this.output = output; } [Sample( DisplayName = "Convert YAML to JSON", Description = "Shows how to convert a YAML document to JSON." )] public void Main() { // convert string/file to YAML object var r = new StringReader(@" scalar: a scalar sequence: - one - two "); var deserializer = new DeserializerBuilder().Build(); var yamlObject = deserializer.Deserialize(r); var serializer = new SerializerBuilder() .JsonCompatible() .Build(); var json = serializer.Serialize(yamlObject); output.WriteLine(json); } } } ``` -------------------------------- ### Deserialize YAML String to Object Source: https://github.com/aaubry/yamldotnet/blob/master/README.md Deserializes a YAML formatted string into a .NET object using YamlDotNet. Requires the YamlDotNet.Serialization namespace and a naming convention. The naming convention should match the YAML structure (e.g., UnderscoredNamingConvention for snake_case keys). ```csharp using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; ... var yml = @" name: George Washington age: 89 height_in_inches: 5.75 addresses: home: street: 400 Mockingbird Lane city: Louaryland state: Hawidaho zip: 99970 "; var deserializer = new DeserializerBuilder() .WithNamingConvention(UnderscoredNamingConvention.Instance) // see height_in_inches in sample yml .Build(); //yml contains a string containing your YAML var p = deserializer.Deserialize(yml); var h = p.Addresses["home"]; System.Console.WriteLine($"{p.Name} is {p.Age} years old and lives at {h.Street} in {h.City}, {h.State}."); // Output: // George Washington is 89 years old and lives at 400 Mockingbird Lane in Louaryland, Hawidaho. ``` -------------------------------- ### Define Contact Class with Validation Attributes Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Deserializer Define a class with validation attributes to be used with a custom deserializer. Ensure all required properties are marked. ```csharp class Contact { [Required] public string Name { get; set; } [Required] public string PhoneNumber { get; set; } } ``` -------------------------------- ### Deserialize YAML with Tag Mapping Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Deserializer Register a YAML tag with a specific .NET type using WithTagMapping. This allows the deserializer to correctly instantiate the specified type when encountering the tag in the YAML. ```csharp var deserializer = new DeserializerBuilder() .WithTagMapping("!contact", typeof(Contact)) .Build(); var contacts = deserializer.Deserialize(yamlInput); foreach (var contact in (IEnumerable)contacts) { Console.WriteLine(contact.GetType().Name); } ``` -------------------------------- ### Discriminate by Unique Key Existence Source: https://github.com/aaubry/yamldotnet/wiki/Deserialization---Type-Discriminators Use AddUniqueKeyTypeDiscriminator to specify type mappings based on the presence of a unique key within a node. This is useful when the key itself indicates the type. ```csharp using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; var yamlKey1 = @" Value: Type1Value: You should be type1 "; var yamlKey2 = @" Value: Type2Value: You should be type2 "; var deserializer = new DeserializerBuilder() .WithTypeDiscriminatingNodeDeserializer((o) => { var keyMappings = new Dictionary { { "Type1Value", typeof(Type1) }, { "Type2Value", typeof(Type2) } }; o.AddUniqueKeyTypeDiscriminator(keyMappings); }) .Build(); var parent = deserializer.Deserialize(yamlKey1); Console.WriteLine("Value Type: " + parent.Value.GetType().ToString()); Console.WriteLine(((Type1)parent.Value).Type1Value.ToString()); parent = deserializer.Deserialize(yamlKey2); Console.WriteLine("Value Type: " + parent.Value.GetType().ToString()); Console.WriteLine(((Type2)parent.Value).Type2Value.ToString()); public class Parent { public TypeObject Value { get; set; } } public abstract class TypeObject { public string ObjectType { get; set; } } public class Type1 : TypeObject { public string Type1Value { get; set; } } public class Type2 : TypeObject { public string Type2Value { get; set; } } ``` -------------------------------- ### Discriminate by Key Value Source: https://github.com/aaubry/yamldotnet/wiki/Deserialization---Type-Discriminators Use AddKeyValueTypeDiscriminator to map YAML values of a specific key to C# types. Ensure the key name in the YAML document exactly matches the string provided. ```csharp using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; var yamlValue1 = @" Property1: Type1 Value: ObjectType: Type1 Type1Value: You should be type1 "; var yamlValue2 = @" Property1: Type2 Value: ObjectType: Type2 Type2Value: You should be type2 "; var deserializer = new DeserializerBuilder() .WithTypeDiscriminatingNodeDeserializer((o) => { IDictionary valueMappings = new Dictionary { { "Type1", typeof(Type1) }, { "Type2", typeof(Type2) } }; o.AddKeyValueTypeDiscriminator("ObjectType", valueMappings); // "ObjectType" must match the name of the key exactly as it appears in the Yaml document. }) .Build(); var parent = deserializer.Deserialize(yamlValue1); Console.WriteLine("Value Type: " + parent.Value.GetType().ToString()); Console.WriteLine(((Type1)parent.Value).Type1Value.ToString()); parent = deserializer.Deserialize(yamlValue2); Console.WriteLine("Value Type: " + parent.Value.GetType().ToString()); Console.WriteLine(((Type2)parent.Value).Type2Value.ToString()); public class Parent { public string Property1 { get; set; } public string Property2 { get; set; } public TypeObject Value { get; set; } } public abstract class TypeObject { public string ObjectType { get; set; } } public class Type1 : TypeObject { public string Type1Value { get; set; } } public class Type2 : TypeObject { public string Type2Value { get; set; } } ``` -------------------------------- ### Deserialize Multiple YAML Documents from a Stream Source: https://github.com/aaubry/yamldotnet/wiki/Samples.DeserializingMultipleDocuments Use this code to deserialize multiple YAML documents from a single stream. It manually parses the stream to process each document individually. ```C# using System.Collections.Generic; using System.IO; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Serialization; using YamlDotNet.Samples.Helpers; using Xunit.Abstractions; namespace YamlDotNet.Samples { public class DeserializingMultipleDocuments { private readonly ITestOutputHelper output; public DeserializingMultipleDocuments(ITestOutputHelper output) { this.output = output; } [Sample( DisplayName = "Deserializing multiple documents", Description = "Explains how to load multiple YAML documents from a stream." )] public void Main() { var input = new StringReader(Document); var deserializer = new DeserializerBuilder().Build(); var parser = new Parser(input); // Consume the stream start event "manually" parser.Expect(); while (parser.Acceptсля) { // Deserialize the document var doc = deserializer.Deserialize>(parser); output.WriteLine("## Document"); foreach (var item in doc) { output.WriteLine(item); } } } private const string Document = @"--- - Prisoner - Goblet - Phoenix --- - Memoirs - Snow - Ghost ..."; } } ``` -------------------------------- ### Configure Deserializer to Ignore Unmatched Properties Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Deserializer Configure the DeserializerBuilder to ignore YAML properties that do not have a corresponding property in the destination .NET object. This prevents exceptions when the YAML contains extra fields. ```csharp var deserializer = new DeserializerBuilder() .IgnoreUnmatchedProperties() .Build(); ``` -------------------------------- ### Configure Default Values Handling in YAML Serialization Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Serializer Modify the serializer's behavior to omit null or default values using `ConfigureDefaultValuesHandling()`. This is useful for reducing the size of the serialized output when certain values are not critical. The `DefaultValuesHandling` enum provides options to preserve all values, omit nulls, or omit default values. ```csharp class Model { public string NullString => null; [DefaultValue("some-default")] public string NullStringWithDefault => null; public int ZeroInteger => 0; public int? NullableInteger => null; [DefaultValue(42)] public int DefaultInteger => 42; } ``` ```csharp var model = new Model(); Console.WriteLine("# DefaultValuesHandling.Preserve (default)"); new SerializerBuilder() .ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve) .Build() .Serialize(Console.Out, model); Console.WriteLine("# DefaultValuesHandling.OmitNull"); new SerializerBuilder() .ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull) .Build() .Serialize(Console.Out, model); Console.WriteLine("# DefaultValuesHandling.OmitDefaults"); new SerializerBuilder() .ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitDefaults) .Build() .Serialize(Console.Out, model); ``` -------------------------------- ### Deserialize YAML to a Known Type Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Deserializer Deserialize a YAML string into a List of Contact objects when the structure is known beforehand. Ensure the C# class matches the YAML structure. ```csharp var deserializer = new DeserializerBuilder() .Build(); var contacts = deserializer.Deserialize>(yamlInput); Console.WriteLine(contacts[0]); ``` -------------------------------- ### Disable Aliases in YAML Serialization Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Serializer Use `DisableAliases()` to prevent the serializer from using anchors and aliases for duplicate objects. This causes each instance of an object to be emitted fully, which can be beneficial if duplicate references are not desired or if the performance cost of walking the object graph twice is acceptable. ```csharp var address = new { street = "123 Tornado Alley, Suite 16", city = "East Westville", state = "KS" }; var receipt = new { bill_to = address, ship_to = address, }; Console.WriteLine("# First, with aliases enabled (default)"); new SerializerBuilder() .Build() .Serialize(Console.Out, receipt); Console.WriteLine("# Then, with aliases disabled"); new SerializerBuilder() .DisableAliases() .Build() .Serialize(Console.Out, receipt); ``` -------------------------------- ### Custom ValidatingNodeDeserializer Source: https://github.com/aaubry/yamldotnet/wiki/Samples.ValidatingDuringDeserialization Implements INodeDeserializer to wrap an existing deserializer and add validation logic using Validator.ValidateObject. This allows for custom validation rules to be applied to deserialized objects. ```C# public class ValidatingNodeDeserializer : INodeDeserializer { private readonly INodeDeserializer _nodeDeserializer; public ValidatingNodeDeserializer(INodeDeserializer nodeDeserializer) { _nodeDeserializer = nodeDeserializer; } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object value) { if (_nodeDeserializer.Deserialize(parser, expectedType, nestedObjectDeserializer, out value)) { var context = new ValidationContext(value, null, null); Validator.ValidateObject(value, context, true); return true; } return false; } } ``` -------------------------------- ### Override Attribute for Deserialization Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Deserializer Use `WithAttributeOverride` to associate custom attributes with class members during deserialization. This is useful for mapping YAML aliases to C# properties without modifying the original class. ```yaml full_name: Oz-Ware PhoneNumber: 123456789 ``` ```csharp var deserializer = new DeserializerBuilder() .WithAttributeOverride( c => c.Name, new YamlMemberAttribute { Alias = "full_name" } ) .Build(); var contact = deserializer.Deserialize(yamlInput); Console.WriteLine(contact); ``` -------------------------------- ### Override Member Attribute with YamlMember Source: https://github.com/aaubry/yamldotnet/wiki/Serialization.Serializer Applies custom YamlMember attributes to class members without modifying the original class. Use this to control serialization aspects like ScalarStyle for specific properties. ```csharp var serializer = new SerializerBuilder() .WithAttributeOverride( c => c.RepresentativeName, new YamlMemberAttribute { ScalarStyle = ScalarStyle.DoubleQuoted } ) .Build(); serializer.Serialize(Console.Out, contacts); ``` -------------------------------- ### Data Class with Required Field Source: https://github.com/aaubry/yamldotnet/wiki/Samples.ValidatingDuringDeserialization Defines a simple Data class with a 'Name' property marked as [Required]. This attribute is used by the Validator.ValidateObject method within the ValidatingNodeDeserializer to enforce that the 'Name' field must be present during deserialization. ```C# public class Data { [Required] public string Name { get; set; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.