-Added support for missing JSON errors to error handling

This commit is contained in:
JamesNK
2011-07-31 23:10:38 +00:00
parent 2da612396d
commit ce2b5e02e0
2 changed files with 124 additions and 68 deletions
@@ -25,11 +25,13 @@
#if !PocketPC #if !PocketPC
using System; using System;
using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Runtime.Serialization; using System.Runtime.Serialization;
using System.Text; using System.Text;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Tests; using Newtonsoft.Json.Tests;
using Newtonsoft.Json.Tests.TestObjects; using Newtonsoft.Json.Tests.TestObjects;
using NUnit.Framework; using NUnit.Framework;
@@ -288,6 +290,47 @@ namespace Newtonsoft.Json.Tests.Serialization
}", json); }", json);
} }
#endif #endif
public void WhenSerializationErrorDetectedBySerializer_ThenCallbackIsCalled()
{
// Verify contract is properly finding our callback
var resolver = new DefaultContractResolver().ResolveContract(typeof(FooEvent));
Debug.Assert(resolver.OnError != null);
Debug.Assert(resolver.OnError == typeof(FooEvent).GetMethod("OnError", BindingFlags.Instance | BindingFlags.NonPublic));
var serializer = JsonSerializer.Create(new JsonSerializerSettings
{
// If I don't specify Error here, the callback isn't called
// either, but no exception is thrown.
MissingMemberHandling = MissingMemberHandling.Error,
});
// This throws with missing member exception, rather than calling my callback.
var foo = serializer.Deserialize<FooEvent>(new JsonTextReader(new StringReader("{ Id: 25 }")));
// When fixed, this would pass.
Debug.Assert(foo.Identifier == 25);
}
public class FooEvent
{
public int Identifier { get; set; }
[OnError]
private void OnError(StreamingContext context, ErrorContext error)
{
this.Identifier = 25;
// Here we could for example manually copy the
// persisted "Id" value into the renamed "Identifier"
// property, etc.
error.Handled = true;
// We never get here :(
Console.WriteLine("Error has been fixed");
}
}
} }
} }
#endif #endif
@@ -65,7 +65,7 @@ namespace Newtonsoft.Json.Serialization
if (reader.TokenType == JsonToken.StartArray) if (reader.TokenType == JsonToken.StartArray)
{ {
if (contract is JsonArrayContract) if (contract is JsonArrayContract)
PopulateList(CollectionUtils.CreateCollectionWrapper(target), reader, null, (JsonArrayContract)contract); PopulateList(CollectionUtils.CreateCollectionWrapper(target), reader, null, (JsonArrayContract) contract);
else else
throw new JsonSerializationException("Cannot populate JSON array onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); throw new JsonSerializationException("Cannot populate JSON array onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType));
} }
@@ -82,9 +82,9 @@ namespace Newtonsoft.Json.Serialization
} }
if (contract is JsonDictionaryContract) if (contract is JsonDictionaryContract)
PopulateDictionary(CollectionUtils.CreateDictionaryWrapper(target), reader, (JsonDictionaryContract)contract, id); PopulateDictionary(CollectionUtils.CreateDictionaryWrapper(target), reader, (JsonDictionaryContract) contract, id);
else if (contract is JsonObjectContract) else if (contract is JsonObjectContract)
PopulateObject(target, reader, (JsonObjectContract)contract, id); PopulateObject(target, reader, (JsonObjectContract) contract, id);
else else
throw new JsonSerializationException("Cannot populate JSON object onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType)); throw new JsonSerializationException("Cannot populate JSON object onto type '{0}'.".FormatWith(CultureInfo.InvariantCulture, objectType));
} }
@@ -143,7 +143,7 @@ namespace Newtonsoft.Json.Serialization
{ {
ValidationUtils.ArgumentNotNull(reader, "reader"); ValidationUtils.ArgumentNotNull(reader, "reader");
if (contract != null && contract.UnderlyingType == typeof(JRaw)) if (contract != null && contract.UnderlyingType == typeof (JRaw))
{ {
return JRaw.Create(reader); return JRaw.Create(reader);
} }
@@ -232,14 +232,14 @@ namespace Newtonsoft.Json.Serialization
return EnsureType(reader.Value, CultureInfo.InvariantCulture, objectType); return EnsureType(reader.Value, CultureInfo.InvariantCulture, objectType);
case JsonToken.String: case JsonToken.String:
// convert empty string to null automatically for nullable types // convert empty string to null automatically for nullable types
if (string.IsNullOrEmpty((string)reader.Value) && if (string.IsNullOrEmpty((string) reader.Value) &&
objectType != null && objectType != null &&
ReflectionUtils.IsNullableType(objectType)) ReflectionUtils.IsNullableType(objectType))
return null; return null;
// string that needs to be returned as a byte array should be base 64 decoded // string that needs to be returned as a byte array should be base 64 decoded
if (objectType == typeof(byte[])) if (objectType == typeof (byte[]))
return Convert.FromBase64String((string)reader.Value); return Convert.FromBase64String((string) reader.Value);
return EnsureType(reader.Value, CultureInfo.InvariantCulture, objectType); return EnsureType(reader.Value, CultureInfo.InvariantCulture, objectType);
case JsonToken.StartConstructor: case JsonToken.StartConstructor:
@@ -249,12 +249,12 @@ namespace Newtonsoft.Json.Serialization
return constructorName; return constructorName;
case JsonToken.Null: case JsonToken.Null:
case JsonToken.Undefined: case JsonToken.Undefined:
if (objectType == typeof(DBNull)) if (objectType == typeof (DBNull))
return DBNull.Value; return DBNull.Value;
return EnsureType(reader.Value, CultureInfo.InvariantCulture, objectType); return EnsureType(reader.Value, CultureInfo.InvariantCulture, objectType);
case JsonToken.Raw: case JsonToken.Raw:
return new JRaw((string)reader.Value); return new JRaw((string) reader.Value);
case JsonToken.Comment: case JsonToken.Comment:
// ignore // ignore
break; break;
@@ -471,11 +471,11 @@ namespace Newtonsoft.Json.Serialization
private bool HasDefinedType(Type type) private bool HasDefinedType(Type type)
{ {
return (type != null && type != typeof(object) && !typeof(JToken).IsAssignableFrom(type) return (type != null && type != typeof (object) && !typeof (JToken).IsAssignableFrom(type)
#if !(NET35 || NET20 || WINDOWS_PHONE) #if !(NET35 || NET20 || WINDOWS_PHONE)
&& type != typeof(IDynamicMetaObjectProvider) && type != typeof (IDynamicMetaObjectProvider)
#endif #endif
); );
} }
private object EnsureType(object value, CultureInfo culture, Type targetType) private object EnsureType(object value, CultureInfo culture, Type targetType)
@@ -537,7 +537,7 @@ namespace Newtonsoft.Json.Serialization
useExistingValue = (currentValue != null useExistingValue = (currentValue != null
&& !property.PropertyType.IsArray && !property.PropertyType.IsArray
&& !ReflectionUtils.InheritsGenericDefinition(property.PropertyType, typeof(ReadOnlyCollection<>)) && !ReflectionUtils.InheritsGenericDefinition(property.PropertyType, typeof (ReadOnlyCollection<>))
&& !property.PropertyType.IsValueType); && !property.PropertyType.IsValueType);
} }
@@ -624,10 +624,12 @@ namespace Newtonsoft.Json.Serialization
switch (reader.TokenType) switch (reader.TokenType)
{ {
case JsonToken.PropertyName: case JsonToken.PropertyName:
object keyValue; object keyValue = reader.Value;
try try
{ {
keyValue = EnsureType(reader.Value, CultureInfo.InvariantCulture, contract.DictionaryKeyType); try
{
keyValue = EnsureType(keyValue, CultureInfo.InvariantCulture, contract.DictionaryKeyType);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -637,8 +639,6 @@ namespace Newtonsoft.Json.Serialization
if (!ReadForType(reader, contract.DictionaryValueType, null)) if (!ReadForType(reader, contract.DictionaryValueType, null))
throw new JsonSerializationException("Unexpected end when deserializing object."); throw new JsonSerializationException("Unexpected end when deserializing object.");
try
{
dictionary[keyValue] = CreateValueNonProperty(reader, contract.DictionaryValueType, GetContractSafe(contract.DictionaryValueType)); dictionary[keyValue] = CreateValueNonProperty(reader, contract.DictionaryValueType, GetContractSafe(contract.DictionaryValueType));
} }
catch (Exception ex) catch (Exception ex)
@@ -802,7 +802,7 @@ namespace Newtonsoft.Json.Serialization
if (contract.DefaultCreator != null && if (contract.DefaultCreator != null &&
(!contract.DefaultCreatorNonPublic || Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor)) (!contract.DefaultCreatorNonPublic || Serializer.ConstructorHandling == ConstructorHandling.AllowNonPublicDefaultConstructor))
newObject = (IDynamicMetaObjectProvider)contract.DefaultCreator(); newObject = (IDynamicMetaObjectProvider) contract.DefaultCreator();
else else
throw new JsonSerializationException("Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType)); throw new JsonSerializationException("Unable to find a default constructor to use for type {0}.".FormatWith(CultureInfo.InvariantCulture, contract.UnderlyingType));
@@ -811,6 +811,8 @@ namespace Newtonsoft.Json.Serialization
contract.InvokeOnDeserializing(newObject, Serializer.Context); contract.InvokeOnDeserializing(newObject, Serializer.Context);
int initialDepth = reader.Depth;
bool exit = false; bool exit = false;
do do
{ {
@@ -818,6 +820,9 @@ namespace Newtonsoft.Json.Serialization
{ {
case JsonToken.PropertyName: case JsonToken.PropertyName:
string memberName = reader.Value.ToString(); string memberName = reader.Value.ToString();
try
{
if (!reader.Read()) if (!reader.Read())
throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName)); throw new JsonSerializationException("Unexpected end when setting {0}'s value.".FormatWith(CultureInfo.InvariantCulture, memberName));
@@ -829,12 +834,20 @@ namespace Newtonsoft.Json.Serialization
} }
else else
{ {
Type t = (JsonReader.IsPrimitiveToken(reader.TokenType)) ? reader.ValueType : typeof(IDynamicMetaObjectProvider); Type t = (JsonReader.IsPrimitiveToken(reader.TokenType)) ? reader.ValueType : typeof (IDynamicMetaObjectProvider);
object value = CreateValueNonProperty(reader, t, GetContractSafe(t, null)); object value = CreateValueNonProperty(reader, t, GetContractSafe(t, null));
newObject.TrySetMember(memberName, value); newObject.TrySetMember(memberName, value);
} }
}
catch (Exception ex)
{
if (IsErrorHandled(newObject, contract, memberName, ex))
HandleError(reader, initialDepth);
else
throw;
}
break; break;
case JsonToken.EndObject: case JsonToken.EndObject:
exit = true; exit = true;
@@ -889,7 +902,7 @@ namespace Newtonsoft.Json.Serialization
IDictionary<JsonProperty, object> propertyValues = ResolvePropertyAndConstructorValues(contract, reader, objectType); IDictionary<JsonProperty, object> propertyValues = ResolvePropertyAndConstructorValues(contract, reader, objectType);
IDictionary<ParameterInfo, object> constructorParameters = constructorInfo.GetParameters().ToDictionary(p => p, p => (object)null); IDictionary<ParameterInfo, object> constructorParameters = constructorInfo.GetParameters().ToDictionary(p => p, p => (object) null);
IDictionary<JsonProperty, object> remainingPropertyValues = new Dictionary<JsonProperty, object>(); IDictionary<JsonProperty, object> remainingPropertyValues = new Dictionary<JsonProperty, object>();
foreach (KeyValuePair<JsonProperty, object> propertyValue in propertyValues) foreach (KeyValuePair<JsonProperty, object> propertyValue in propertyValues)
@@ -1021,18 +1034,18 @@ namespace Newtonsoft.Json.Serialization
if (hasConverter) if (hasConverter)
return reader.Read(); return reader.Read();
if (t == typeof(byte[])) if (t == typeof (byte[]))
{ {
reader.ReadAsBytes(); reader.ReadAsBytes();
return true; return true;
} }
else if ((t == typeof(decimal) || t == typeof(decimal?))) else if ((t == typeof (decimal) || t == typeof (decimal?)))
{ {
reader.ReadAsDecimal(); reader.ReadAsDecimal();
return true; return true;
} }
#if !NET20 #if !NET20
else if ((t == typeof(DateTimeOffset) || t == typeof(DateTimeOffset?))) else if ((t == typeof (DateTimeOffset) || t == typeof (DateTimeOffset?)))
{ {
reader.ReadAsDateTimeOffset(); reader.ReadAsDateTimeOffset();
return true; return true;
@@ -1067,6 +1080,8 @@ namespace Newtonsoft.Json.Serialization
case JsonToken.PropertyName: case JsonToken.PropertyName:
string memberName = reader.Value.ToString(); string memberName = reader.Value.ToString();
try
{
// attempt exact case match first // attempt exact case match first
// then try match ignoring case // then try match ignoring case
JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName); JsonProperty property = contract.Properties.GetClosestMatchProperty(memberName);
@@ -1085,8 +1100,6 @@ namespace Newtonsoft.Json.Serialization
SetRequiredProperty(reader, property, requiredProperties); SetRequiredProperty(reader, property, requiredProperties);
try
{
SetPropertyValue(property, reader, newObject); SetPropertyValue(property, reader, newObject);
} }
catch (Exception ex) catch (Exception ex)