0

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?

davecove
  • 1,001
  • 4
  • 16
  • 36
  • 1
    I would try [Json.Net](https://json.codeplex.com/) – L.B Sep 12 '16 at 20:49
  • Expanding on @L.B's comment a bit, Json.NET can [convert from JSON to XML](http://www.newtonsoft.com/json/help/html/ConvertingJSONandXML.htm) so you could serialize to json then convert to XML. – dbc Sep 12 '16 at 21:34
  • 1
    Otherwise, see [Excluding some properties during serialization without changing the original class](http://stackoverflow.com/questions/9377414). But take note of [Memory Leak using StreamReader and XmlSerializer](https://stackoverflow.com/questions/23897145) - the serializer should only be constructed once, then cached. – dbc Sep 12 '16 at 21:37

1 Answers1

0

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.

Pedro S Cord
  • 1,301
  • 17
  • 20