简体   繁体   中英

Making a non-serializable vendor class serializable

I am using a class from a vendor's DLL that is not XML serializable because one of the class members is an Interface.

However, I do need to serialize an instance of the class.

How can I tell the XmlSerializer to ignore the interface and serialize everything else?

You can do 2 things:

1) Create a class with every thing you want, populate it with the your vendor class, then you serialize it.

Check adapter design pattern

2) Use Json.Net. Once I need to serialize the IPagedList that have metadata and I did this:

    public static string SerializePagedList(IPagedList<T> pagedList)
    {
        string result = JsonConvert.SerializeObject(
           // new anonymous class with everything I wanted
            new
            {
                Items = pagedList,
                MetaData = pagedList.GetMetaData()
            },
            new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            });
        return result;
    }

I hope that it helps.

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