Consider the following code (.NET Framework 4.8 c#)
using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
namespace SerialisationTest
{
class Program
{
class ErrorData
{
public int ErrorCode { get; set; }
public string ErrorDescription { get; set; }
}
[Serializable]
class ErrorDataList : List<ErrorData>
{
}
class DataResponse<TResponseType>
{
public TResponseType Data { get; set; }
public List<ErrorData> ErrorList { get; set; }
}
class DataResponse2<TResponseType>
{
public TResponseType Data { get; set; }
public ErrorDataList ErrorList { get; set; }
}
static void Main(string[] args)
{
JavaScriptSerializer serial = new JavaScriptSerializer();
ErrorData error = new ErrorData
{
ErrorCode = 1,
ErrorDescription = "ERRORS OCCURRED"
};
DataResponse<string> dataResponse = new DataResponse<string>
{
Data = "HELLO WORLD",
ErrorList = new List<ErrorData>() { error }
};
string serialised = serial.Serialize(dataResponse);
dataResponse = serial.Deserialize<DataResponse<string>>(serialised);
DataResponse2<string> dataResponse2 = new DataResponse2<string>
{
Data = "HELLO WORLD",
ErrorList = new ErrorDataList() { error }
};
string serialised2 = serial.Serialize(dataResponse);
dataResponse2 = serial.Deserialize<DataResponse2<string>>(serialised2);
}
}
}
dataResponse serialises and deserialises fine, but dataResponse2 fails to deserialise with the error
The value "System.Collections.Generic.Dictionary`2[System.String,System.Object]" is not of type "SerialisationTest.Program+ErrorData" and cannot be used in this generic collection.
I marked the ErrorDataList class as Serializable in a vain attempt to rectify the issue (it is the same with or without the attribute). What is causing this error?