Serialize XmlDocument to Json using System.Text.Json in .Net Core 3.1 Web Api project

6.3k views Asked by At

I'm switching from Newtonsoft.Json to System.Text.Json in a .net Core 3.1 web api project. The project is a legacy .net core web api project with hundreds of clients. Some of the controller endpoints returns XmlDocuments. Using Newtonsoft.Json to serialize the XmlDocuments to Json worked fine and gave expected result. Unfortunately when switching to System.Text.Json the serialization does not work the same.

Example using System; using System.Xml;

public class Program
{
    public static void Main()
    {
        var xml = @"<root><items><item id=""1"">item 1</item><item id=""2"">item 2</item></items></root>";
        var xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xml);        
        Console.WriteLine($"Xml: {xml}");
        Console.WriteLine($"XmlDocument xml: {xmlDoc.ToString()}");
        
        var serializedXml = System.Text.Json.JsonSerializer.Serialize(xmlDoc);
        Console.WriteLine($"Serialized xml using System.Text.Json: {serializedXml}");
        
        serializedXml = Newtonsoft.Json.JsonConvert.SerializeObject(xmlDoc);
        Console.WriteLine($"Serialized xml using Newtonsoft.Json: {serializedXml}");
    }
}

.net fiddler example

Result

Xml: <root><items><item id="1">item 1</item><item id="2">item 2</item></items></root>
XmlDocument xml: System.Xml.XmlDocument
Serialized xml using System.Text.Json: [[[[[]],[[]]]]]
Serialized xml using Newtonsoft.Json: {"root":{"items":{"item":[{"@id":"1","#text":"item 1"}, 
{"@id":"2","#text":"item 2"}]}}}

Is there any way to use System.Text.Json to automatically serialize XmlDocuments in .net Core 3.1 web api besides:

  1. Using Newtsoft.Json serializer as standard for the whole project
  2. Creating a custom XmlDocument TextOutputFormatter and adding it to output formater
0

There are 0 answers