-Fixed deserializing generic only IList types with a constructor override

This commit is contained in:
James Newton-King
2016-11-05 23:21:34 +13:00
parent 989d980be6
commit 803403ae21
2 changed files with 114 additions and 1 deletions
@@ -1944,6 +1944,112 @@ namespace Newtonsoft.Json.Tests.Serialization
Assert.AreEqual("replaced!", result.Person["groups"]);
}
#endif
[Test]
public void GenericIListAndOverrideConstructor()
{
MyClass deserialized = JsonConvert.DeserializeObject<MyClass>(@"[""apple"", ""monkey"", ""goose""]");
Assert.AreEqual("apple", deserialized[0]);
Assert.AreEqual("monkey", deserialized[1]);
Assert.AreEqual("goose", deserialized[2]);
}
public class MyClass : IList<string>
{
private List<string> _storage;
[JsonConstructor]
private MyClass()
{
_storage = new List<string>();
}
public MyClass(IEnumerable<string> source)
{
_storage = new List<string>(source);
}
//Below is generated by VS to implement IList<string>
public string this[int index]
{
get
{
return ((IList<string>)_storage)[index];
}
set
{
((IList<string>)_storage)[index] = value;
}
}
public int Count
{
get
{
return ((IList<string>)_storage).Count;
}
}
public bool IsReadOnly
{
get
{
return ((IList<string>)_storage).IsReadOnly;
}
}
public void Add(string item)
{
((IList<string>)_storage).Add(item);
}
public void Clear()
{
((IList<string>)_storage).Clear();
}
public bool Contains(string item)
{
return ((IList<string>)_storage).Contains(item);
}
public void CopyTo(string[] array, int arrayIndex)
{
((IList<string>)_storage).CopyTo(array, arrayIndex);
}
public IEnumerator<string> GetEnumerator()
{
return ((IList<string>)_storage).GetEnumerator();
}
public int IndexOf(string item)
{
return ((IList<string>)_storage).IndexOf(item);
}
public void Insert(int index, string item)
{
((IList<string>)_storage).Insert(index, item);
}
public bool Remove(string item)
{
return ((IList<string>)_storage).Remove(item);
}
public void RemoveAt(int index)
{
((IList<string>)_storage).RemoveAt(index);
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IList<string>)_storage).GetEnumerator();
}
}
}
#if !NET20 && !PORTABLE40
@@ -1176,8 +1176,15 @@ namespace Newtonsoft.Json.Serialization
}
else
{
object list = contract.OverrideCreator();
if (contract.ShouldCreateWrapper)
{
list = contract.CreateWrapper(list);
}
createdFromNonDefaultCreator = false;
return (IList)contract.OverrideCreator();
return (IList)list;
}
}
else if (contract.IsReadOnlyOrFixedSize)