-Added additional error checking around $ref property

This commit is contained in:
JamesNK
2010-03-17 07:27:57 +00:00
parent 6d67aefac7
commit 0b42b38f34
2 changed files with 44 additions and 0 deletions
@@ -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<string, object>();
reference.Add("$ref", "Persons");
reference.Add("$id", 1);
var child = new Dictionary<string, object>();
child.Add("_id", 2);
child.Add("Name", "Isabell");
child.Add("Father", reference);
var json = JsonConvert.SerializeObject(child);
JsonConvert.DeserializeObject<Dictionary<string, object>>(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<string, object>();
reference.Add("$ref", 1);
reference.Add("$id", 1);
var child = new Dictionary<string, object>();
child.Add("_id", 2);
child.Add("Name", "Isabell");
child.Add("Father", reference);
var json = JsonConvert.SerializeObject(child);
JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
}
}
}
@@ -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))