-Improve error message when attempting to deserialize to an interface or abstract class
This commit is contained in:
@@ -1225,5 +1225,39 @@ keyword such as type of business.""
|
|||||||
|
|
||||||
GoogleMapGeocoderStructure jsonGoogleMapGeocoder = JsonConvert.DeserializeObject<GoogleMapGeocoderStructure>(json);
|
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));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -493,7 +493,11 @@ namespace Newtonsoft.Json
|
|||||||
{
|
{
|
||||||
object newObject;
|
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);
|
newObject = Activator.CreateInstance(objectType);
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user