Convert through a type whenever you can. XML and JSON don’t describe data the same way, and a type is where you say what each part means.
Convert through a type
Both serializers can map the same class.Delivery is an ordinary class with two attributes for XmlEssentials and one for System.Text.Json:
Delivery.cs
[XmlAttribute] writes Id as an XML attribute, which JSON has no counterpart for. [XmlElement("item")] and [JsonPropertyName("items")] give the list the name each format expects: a repeated item element in XML, and an items array in JSON.
Create the options for each serializer once and reuse them. The two sets mirror each other:
Program.cs
XML to JSON
Deserialize the XML withXmlSerializer, and serialize the object with JsonSerializer:
Program.cs
JSON to XML
The other direction is the same two calls with the serializers swapped:Program.cs
What to line up between the two serializers
A conversion through a type is only as faithful as the two mappings. Check these four things:- Names. Set the same naming policy on both sides, or name members with
[XmlPropertyName]and[JsonPropertyName]. See Customize names. - Null values.
XmlSerializerwrites anullmember as an element withxsi:nil="true", andJsonSerializerwritesnull. To leavenullmembers out of both, setDefaultIgnoreConditiontoWhenWritingNullon both sets of options. See Null and nil. - The root element. A JSON document has no name, and an XML document must have one.
XmlSerializertakes it from the type name or from[XmlRoot]. - What only XML has. Attributes, namespaces, and mixed content have no JSON form. They map to ordinary properties of your class, and System.Text.Json writes those properties like any others. See Coming from System.Text.Json.
Convert UTF-8 without reflection
Both serializers read and write UTF-8 directly, and both have a source generator. Together they convert a document without creating a string of it, in an application that’s trimmed or compiled with Native AOT. Declare one context for each serializer:DeliveryContexts.cs
Program.cs
XmlSerializer also reads from and writes to a Stream, as JsonSerializer does. See Use source generation and Native AOT.
View the complete sample on GitHub
Convert without a type
When you have no class for the data, convert between the two mutable trees:XmlNode in XmlEssentials and JsonNode in System.Text.Json. Neither library has a method that does this for you, because there’s no single right answer for what an attribute or a repeated element becomes in JSON. You choose a convention and write a short method for each direction.
The methods in this article use a common convention:
The convention uses local names and doesn’t carry namespaces. For a document with namespaces, convert through a type.
XML to JSON
ToJson converts one element, and calls itself for each child element. Append turns a property into an array when a second element has the same name.
Program.cs
Program.cs
@, the array has the name of its elements, and every value is a string, because XML text doesn’t say whether 1042 is a number.
Comments and processing instructions are left out. JSON has nowhere to put them.
JSON to XML
ToXml creates an element for one JSON value, and Fill gives the element its content.
Program.cs
Utf8XmlWriter:
Program.cs
id is an element, because nothing in the JSON marks it as an attribute, and each item of the array is an element named items.
A JSON property name that isn’t a valid XML name, such as first name or 2024, throws an XmlException when the tree is written. Rename those properties before you convert them.
View the complete sample on GitHub
What the trees can’t carry across
A conversion through the trees isn’t reversible. The following code takes a JSON document to XML and back with the two methods above:Program.cs
- The number is a string. XML text has no type.
1042and"1042"are the same element. - The Boolean is a string, for the same reason.
- The array of one item is a single value. One
itemselement looks the same as a property that was never an array. An empty array disappears altogether, because it produces no elements.
null survived, as an empty element.
If the consumer of your JSON needs numbers, Booleans, and arrays to stay what they are, the conversion needs to know the shape of the data. That’s what a type gives it, and it’s the reason to convert through a type.
See also
Coming from System.Text.Json
The type-for-type map between the two libraries.
Serialize
Write your own types as XML.
Use XmlNode
Build and change a tree of XML nodes.
Use source generation
Serialize without reflection, for trimming and Native AOT.