Home XmlSerialize nested class with generic XmlElement Maybe<T>
Reply: 0

XmlSerialize nested class with generic XmlElement Maybe<T>

zman Published in 2017-12-07 16:10:56Z

I'm trying to serialize and deserialize a class which has a property which should support the type Maybe<T>

public class Node
    [XmlElement(..., typeof(...))
    ... (many more [XmlElement...]'s here, one for each supported type)
    [XmlElement("Maybe", typeof(MaybeV1<>))]
    public object Data { get; set; }

    public List<Node> Children { get; set; }

the maybe type is really only just

public class MaybeV1<T>
    public T Entity { get; set; }

and the serialization is just:

var serializer = new XmlSerializer(root.GetType(), KnownTypes.Types);

where known types is just a list of supported types matching the types defined in the XmlElements attributes in the Nodes Data property above.

The above won't work and I have not yet been able to find an elegant way to do this.

The best solution that I have been able to come up with so far is to create a non-generic type MaybeV1 which serializes the type along with the value:

public class MaybeV1
    public object Entity { get; set; }

    public Type Type { get; set; }
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.351592 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO