I am currently working on an api wrapper of an third party XML api. I am hoping to use the same object and endpoint with web api to support both. (almost working)
The issue comes when working with the following type of object:
enum ItemsChoiceType
{
Foo,
Bar,
Baz
}
...
[XmlElement("Foo", typeof(string), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
[XmlElement("Bar", typeof(BarClass), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
[XmlElement("Baz", typeof(string), Form = System.Xml.Schema.XmlSchemaForm.Unqualified)]
[XmlChoiceIdentifier("ItemsElementName")]
public object[] Items
{
get => itemsField;
set => itemsField = value;
}
/// <remarks/>
[XmlElement("ItemsElementName")]
[XmlIgnore()]
public ItemsChoiceType[] ItemsElementName
{
get => itemsElementNameField;
set => itemsElementNameField = value;
}
...
When using the objects the arrays look like this:
obj.Items = new object[]{"This is Foo", "This is Baz", new BarClass()};
obj.ItemsElementName = new ItemsChoiceType[] {Foo, Baz, Bar};
The xml looks like this:
<root>
<Foo>This is Foo</Foo>
<Baz>This is Baz</Baz>
<Bar>/*BarClass xml*/</Bar>
</root>
When converting to json the two arrays serialize fine but deserialization of the BarClass
doesn't get the proper type of BarClass
since its deserializing into an object[] and is a JObject. Reading through the newtonsoft.json documentation has been less than helpful to solve this problem (i have learned a great deal about some other things though).
TypeNameHandling wont work because of the security issues around it. The XML works because the Enum determines the type and name of the XML element in Items.