简体   繁体   中英

JavaScriptSerializer fails to serialise an object with a property inheriting from List<T>

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?

I ended up changing to use NewtonSoft.Json to deserialise and it works fine:

dataResponse2 = JsonConvert.DeserializeObject<DataResponse2<string>>(serialised2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM