Skip to content

Commit

Permalink
Merge pull request #103 from manuc66/bugfix/Multiple_type_discriminat…
Browse files Browse the repository at this point in the history
…ors_in_JSON_silently_passes._#100

Multiple type discriminators in JSON silently passes. #100
  • Loading branch information
manuc66 authored Jun 16, 2020
2 parents b8cfd60 + 42b7844 commit 239eadf
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
11 changes: 10 additions & 1 deletion JsonSubTypes.Tests/DemoKnownSubTypeWithProperty.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,5 +61,14 @@ public void FallBackToPArentWhenNotFound()
var persons = JsonConvert.DeserializeObject<ICollection<Person>>(json);
Assert.AreEqual(typeof(Person), persons.First().GetType());
}

[Test]
public void ThrowIfManyMatches()
{
string json = "{\r\n \"Name\": \"Foo\",\r\n \"Skill\": \"A\",\r\n \"JobTitle\": \"B\"\r\n}";

var jsonSerializationException = Assert.Throws<JsonSerializationException>(() => JsonConvert.DeserializeObject<Person>(json));
Assert.AreEqual("Ambiguous type resolution, expected only one type but got: JsonSubTypes.Tests.DemoKnownSubTypeWithProperty+Employee, JsonSubTypes.Tests.DemoKnownSubTypeWithProperty+Artist", jsonSerializationException.Message);
}
}
}
}
12 changes: 10 additions & 2 deletions JsonSubTypes/JsonSubtypes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ private Type GetTypeByPropertyPresence(JObject jObject, Type parentType)
{
var knownSubTypeAttributes = GetTypesByPropertyPresence(parentType);

return knownSubTypeAttributes
var types = knownSubTypeAttributes
.Select(knownType =>
{
if (TryGetValueInJson(jObject, knownType.Key, out JToken _))
Expand All @@ -295,7 +295,15 @@ private Type GetTypeByPropertyPresence(JObject jObject, Type parentType)

return null;
})
.FirstOrDefault(type => type != null);
.Where(type => type != null)
.ToArray();

if (types.Length == 1)
{
return types[0];
}

throw new JsonSerializationException("Ambiguous type resolution, expected only one type but got: " + String.Join(", ", types.Select(t => t.FullName).ToArray()));
}

internal virtual Dictionary<string, Type> GetTypesByPropertyPresence(Type parentType)
Expand Down

0 comments on commit 239eadf

Please sign in to comment.