I have the following class.
public class Foo
{
[XmlElement("Bar", typeof(Bar))]
[XmlElement("Pub", typeof(Pub))]
public BaseBar Bar { get; set; }
}
I would like to move from XML serialization to JSON (System.Text.Json
) serialization, what is the equivalent for the attribute [XmlElement("Bar", typeof(Bar))]
?
See this sample: https://dotnetfiddle.net/pU8QAU
Edit:
I am looking for a way to define it on property level, so if I have 2 properties I would like to have different names for those.
public class Foo
{
[XmlElement("Bar", typeof(Bar))]
[XmlElement("Pub", typeof(Pub))]
public BaseBar Bar { get; set; }
[XmlElement("Bar2", typeof(Bar))]
[XmlElement("Pub2", typeof(Pub))]
public BaseBar Bar2 { get; set; }
}
See this sample: https://dotnetfiddle.net/M6nla
Edit2:
The given answer by Guru Stron produces this output
{"Bar":{"$type":"Pub" …
I am looking for
{"Pub":{…
Where Pub
should be serialized from the property Bar
if it is of type Pub
.
2
Answers
.NET 7 and latest version of
System.Text.Json
have introduced support for polymorphic json serialization. One way to handle it is to useJsonDerivedTypeAttribute
on the base type specifying all descendants:Prior .NET 7 custom converter could be used to support polymorphic deserialization.
To serialize you data, you even don’t need any element name attribute, if you have the same property name and you don’t need a root class, you can use a Dictionary
output
to deserialize