Skip to content

Commit

Permalink
Merge pull request #1003 from ChristopherMann/yaml-converter-override
Browse files Browse the repository at this point in the history
Support YamlConverterAttribute in attribute overrides

+semver:feature
  • Loading branch information
EdwardCooke authored Nov 10, 2024
2 parents 7923dd8 + 2eb9023 commit 1055eb7
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
44 changes: 44 additions & 0 deletions YamlDotNet.Test/Serialization/TypeConverterAttributeTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,45 @@ namespace YamlDotNet.Test.Serialization
{
public class TypeConverterAttributeTests
{
[Fact]
public void TestConverterInAttributeOverride_Deserializes()
{
var deserializer = new DeserializerBuilder()
.WithAttributeOverride<OuterClassWithoutAttribute>(
c => c.Value,
new YamlConverterAttribute(typeof(AttributedTypeConverter)))
.WithTypeConverter(new AttributedTypeConverter())
.Build();
var yaml = @"Value:
abc: def";
var actual = deserializer.Deserialize<OuterClassWithoutAttribute>(yaml);
Assert.Equal("abc", actual.Value.Key);
Assert.Equal("def", actual.Value.Value);
}

[Fact]
public void TestConverterInAttributeOverride_Serializes()
{
var serializer = new SerializerBuilder()
.WithAttributeOverride<OuterClassWithoutAttribute>(
c => c.Value,
new YamlConverterAttribute(typeof(AttributedTypeConverter)))
.WithTypeConverter(new AttributedTypeConverter())
.Build();
var o = new OuterClassWithoutAttribute
{
Value = new ValueClass
{
Key = "abc",
Value = "def"
}
};
var actual = serializer.Serialize(o).NormalizeNewLines().TrimNewLines();
var expected = @"Value:
abc: def".NormalizeNewLines().TrimNewLines();
Assert.Equal(expected, actual);
}

[Fact]
public void TestConverterOnAttribute_Deserializes()
{
Expand Down Expand Up @@ -94,6 +133,11 @@ public class OuterClass
public ValueClass Value { get; set; }
}

public class OuterClassWithoutAttribute
{
public ValueClass Value { get; set; }
}

public class ValueClass
{
public string Key { get; set; }
Expand Down
3 changes: 2 additions & 1 deletion YamlDotNet/Serialization/YamlAttributeOverridesInspector.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ public Type? TypeOverride
set { baseDescriptor.TypeOverride = value; }
}

public Type? ConverterType => baseDescriptor.ConverterType;
public Type? ConverterType =>
GetCustomAttribute<YamlConverterAttribute>()?.ConverterType ?? baseDescriptor.ConverterType;

public int Order
{
Expand Down

0 comments on commit 1055eb7

Please sign in to comment.