Skip to content

Commit 25f8511

Browse files
author
Chris Nussbaum
committed
Throw an exception on duplicate keys
1 parent 78b1ab3 commit 25f8511

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

YamlDotNet.Test/Serialization/DeserializerTest.cs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
using System.Linq;
2525
using FluentAssertions;
2626
using Xunit;
27+
using YamlDotNet.Core;
2728
using YamlDotNet.Serialization;
2829
using YamlDotNet.Serialization.NamingConventions;
2930

@@ -216,7 +217,6 @@ public void NewLinesInKeys()
216217
Assert.Equal($"value\na\nb", dictionary.First().Value);
217218
}
218219

219-
220220
[Theory]
221221
[InlineData(".nan", System.Single.NaN)]
222222
[InlineData(".NaN", System.Single.NaN)]
@@ -283,6 +283,23 @@ public void DeserializeScalarEdgeCases(IConvertible value, Type type)
283283
result.Should().Be(value);
284284
}
285285

286+
[Fact]
287+
public void Deserialize_YamlWithDuplicateKeys_ThrowsYamlException()
288+
{
289+
var yaml = @"
290+
name: Jack
291+
momentOfBirth: 1983-04-21T20:21:03.0041599Z
292+
name: Jake
293+
";
294+
295+
var sut = new DeserializerBuilder()
296+
.WithNamingConvention(CamelCaseNamingConvention.Instance)
297+
.Build();
298+
299+
Action act = () => sut.Deserialize<Person>(yaml);
300+
act.ShouldThrow<YamlException>("Because there are duplicate name keys");
301+
}
302+
286303
public class Test
287304
{
288305
public string Value { get; set; }

YamlDotNet/Serialization/NodeDeserializers/ObjectNodeDeserializer.cs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
// SOFTWARE.
2121

2222
using System;
23+
using System.Collections.Generic;
2324
using System.Runtime.Serialization;
2425
using YamlDotNet.Core;
2526
using YamlDotNet.Core.Events;
@@ -52,11 +53,17 @@ bool INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func<IPars
5253
var implementationType = Nullable.GetUnderlyingType(expectedType) ?? expectedType;
5354

5455
value = objectFactory.Create(implementationType);
56+
var consumedProperties = new List<string>();
5557
while (!parser.TryConsume<MappingEnd>(out var _))
5658
{
5759
var propertyName = parser.Consume<Scalar>();
60+
if (consumedProperties.Contains(propertyName.Value))
61+
{
62+
throw new YamlException(propertyName.Start, propertyName.End, $"Encountered duplicate property {propertyName.Value}");
63+
}
5864
try
5965
{
66+
consumedProperties.Add(propertyName.Value);
6067
var property = typeDescriptor.GetProperty(implementationType, null, propertyName.Value, ignoreUnmatched);
6168
if (property == null)
6269
{

0 commit comments

Comments
 (0)