diff --git a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs index 9e78a062..48939998 100644 --- a/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs +++ b/Src/Newtonsoft.Json.Tests/Serialization/JsonSerializerTest.cs @@ -3209,5 +3209,43 @@ keyword such as type of business."" Assert.AreEqual(p.Name, "Existing,Appended"); } + + [Test] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "Additional content found in JSON reference object. A JSON reference object should only have a $ref property.")] + public void SerializeRefAdditionalContent() + { + //Additional text found in JSON string after finishing deserializing object. + //Test 1 + var reference = new Dictionary(); + reference.Add("$ref", "Persons"); + reference.Add("$id", 1); + + var child = new Dictionary(); + child.Add("_id", 2); + child.Add("Name", "Isabell"); + child.Add("Father", reference); + + var json = JsonConvert.SerializeObject(child); + JsonConvert.DeserializeObject>(json); + } + + [Test] + [ExpectedException(typeof(JsonSerializationException), ExpectedMessage = "JSON reference $ref property must have a string value.")] + public void SerializeRefBadType() + { + //Additional text found in JSON string after finishing deserializing object. + //Test 1 + var reference = new Dictionary(); + reference.Add("$ref", 1); + reference.Add("$id", 1); + + var child = new Dictionary(); + child.Add("_id", 2); + child.Add("Name", "Isabell"); + child.Add("Father", reference); + + var json = JsonConvert.SerializeObject(child); + JsonConvert.DeserializeObject>(json); + } } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index 740122ad..83da8400 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -299,9 +299,15 @@ namespace Newtonsoft.Json.Serialization if (string.Equals(propertyName, JsonTypeReflector.RefPropertyName, StringComparison.Ordinal)) { CheckedRead(reader); + if (reader.TokenType != JsonToken.String) + throw new JsonSerializationException("JSON reference {0} property must have a string value.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); + string reference = reader.Value.ToString(); CheckedRead(reader); + if (reader.TokenType == JsonToken.PropertyName) + throw new JsonSerializationException("Additional content found in JSON reference object. A JSON reference object should only have a {0} property.".FormatWith(CultureInfo.InvariantCulture, JsonTypeReflector.RefPropertyName)); + return Serializer.ReferenceResolver.ResolveReference(reference); } else if (string.Equals(propertyName, JsonTypeReflector.TypePropertyName, StringComparison.Ordinal))