-Improve error message when attempting to deserialize to an interface or abstract class

This commit is contained in:
JamesNK
2009-02-08 08:57:45 +00:00
parent 50cca1ec0b
commit eedb01645a
2 changed files with 39 additions and 1 deletions
@@ -1225,5 +1225,39 @@ keyword such as type of business.""
GoogleMapGeocoderStructure jsonGoogleMapGeocoder = JsonConvert.DeserializeObject<GoogleMapGeocoderStructure>(json);
}
public class Co : ICo
{
public String Name { get; set; }
}
public interface ICo
{
String Name { get; set; }
}
public interface ITest
{
ICo co { get; set; }
}
public class Test : ITest
{
public ICo co { get; set; }
public Test()
{
}
}
[Test]
[ExpectedException(typeof(JsonSerializationException), ExpectedMessage = @"Could not create an instance of type Newtonsoft.Json.Tests.JsonSerializerTest+ICo. Type is an interface or abstract class and cannot be instantated.")]
public void DeserializeInterfaceProperty()
{
Test testClass = new Test();
testClass.co = new Co();
String strFromTest = JsonConvert.SerializeObject(testClass);
Test testFromDe = (Test)JsonConvert.DeserializeObject(strFromTest, typeof(Test));
}
}
}
+5 -1
View File
@@ -493,7 +493,11 @@ namespace Newtonsoft.Json
{
object newObject;
if (ReflectionUtils.HasDefaultConstructor(objectType))
if (objectType.IsInterface || objectType.IsAbstract)
{
throw new JsonSerializationException("Could not create an instance of type {0}. Type is an interface or abstract class and cannot be instantated.".FormatWith(CultureInfo.InvariantCulture, objectType));
}
else if (ReflectionUtils.HasDefaultConstructor(objectType))
{
newObject = Activator.CreateInstance(objectType);