JSON to XML / XML to JSON conversion in .NET Core

JSON is a preferred format for transferring data over the wire in modern web
apps. However, at times you need to deal with XML data format. Moreover, you
might want to handle JSON and XML in the same application. For example, you
might be receiving data in JSON from a Web API and then you might want to feed
it to another service that expects input in XML format. Such situations are
common when you are integrating old and new software systems.
In such scenarios you might want to convert XML data into its JSON equivalent
and vice versa. There can be two approaches to handle such data format
conversion:
- Text to Text conversion
- Text to Object to Text conversion
In the first approach you directly convert XML to its JSON equivalent and
vice a versa. In this approach you don't need to have any C# object that maps to
the data being converted. It is more like parsing one format and converting it
to another format without bothering much about the underlying object. You can
either write your own parsing logic or use some third-party library such as
Json.NET to accomplish such a conversion.
In the second approach you first deserialize XML data into a C# object and
then serialize the C# object to JSON. If you wish to convert from JSON to XML
similar process will be followed - JSON to C# object and C# object to XML. To
follow this approach you can use .NET Core's XmlSerializer and JsonSerializer
classes.
In the remainder of this article you will use the second technique to convert
between XML and JSON formats. Let's get going.
As an example let's assume that there is a class named Employee that holds
the application data.
public class Employee
{
public int EmployeeID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
}
Serialize Employee to XML
First of all let's see how an Employee object can be serialized into XML and
JSON formats using JsonSerializer and XmlSerializer classes respectively.
We will write a helper class for this purpose - JsonXmlHelper. The
EmployeeToXml() method of this helper class is shown below:
public static string EmployeeToXml(Employee emp)
{
XmlSerializer xmlSerializer = new XmlSerializer
(typeof(Employee));
using (StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, emp);
return textWriter.ToString();
}
}
The EmployeeToXml() method accepts an Employee object and returns its XML
equivalent to the caller.
Inside, the EmployeeToXml() method uses XmlSerializer class from
System.Xml.Serialization namespace. The .NET Type of the class we wish to
serialize (Employee in this case) is passed to the constructor of XmlSerializer.
Then a new instance of StringWriter is created. The XmlSerializer writes into
this StringWriter when Serialize() method is called. The Serialize() method
takes two parameters - a TextWriter implementation (StringWriter in this case)
and an object to serialize.
To get the XML serialized data from the StringWriter its ToString() method is
called. The XML data is returned to the caller.
Serialize Employee to JSON
Now that you know how to serialize and Employee object into JSON, let's
serialize an Employee using JSON format. Consider the EmployeeToJson() method
shown below:
public static string EmployeeToJson(Employee emp)
{
return JsonSerializer.Serialize(emp);
}
This code is quite simple and straightforward. It uses JsonSerializer class
from System.Text.Json namespace. The Serialize() method of JsonSerializer
accepts an object to be serialized and returns a JSON string. The JSON string is
returned to the caller.
You can use the EmployeeToXml() and EmployeeToJson() method as shown below.
Employee emp = new Employee()
{
EmployeeID = 1,
FirstName = "Nancy",
LastName = "Davolio",
BirthDate = new DateTime(1948, 12, 8)
};
string xml = JsonXmlHelper.EmployeeToXml(emp);
string json = JsonXmlHelper.EmployeeToJson(emp);
A sample XML string returned by EmployeeToXml() method would look like this:
<?xml version="1.0" encoding="UTF-16"?>
<Employee xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<EmployeeID>1</EmployeeID>
<FirstName>Nancy</FirstName>
<LastName>Davolio</LastName>
<BirthDate>1948-12-08T00:00:00</BirthDate>
</Employee>
A sample JSON string returned by EmployeeToJson() method would look like
this:
{
"EmployeeID":1,
"FirstName":"Nancy",
"LastName":"Davolio",
"BirthDate":"1948-12-08T00:00:00"
}
We created the above method so that we can test the next set of methods
easily. In a more realistic case you might be getting the XML / JSON data from a
service or subsystem.
So far so good. Now let's move on to converting from one format to another.
Converting from XML to JSON
In order to convert from XML format to JSON format you need to first
deserialize XML to get an Employee object. Then you can serialize the Employee
object into JSON. This is done by XmlToJson() method.
public static string XmlToJson(string xmlData)
{
Employee emp;
XmlSerializer xmlSerializer =
new XmlSerializer(typeof(Employee));
using (StringReader textReader =
new StringReader(xmlData))
{
emp = (Employee)xmlSerializer.
Deserialize(textReader);
}
return EmployeeToJson(emp);
}
The XmlToJson() method accepts a string containing XML version of an Employee
object and returns a JSON string representing the same Employee data.
Inside, the code creates an XmlSerializer and StringReader objects. The XML
string passed to the XmlToJson() method is fed to the StringReader. The
StringReader is then supplied to the Deserialize() method of XmlSerializer. The
Deserialize() method deserializes the XML data into an Employee object. The
Employee object is then passed to EmployeeToJson() method to get its JSON
equivalent. The JSON string is then returned to the caller.
A sample usage of XmlToJson() would look like this:
string xml = JsonXmlHelper.EmployeeToXml(emp);
string json = JsonXmlHelper.XmlToJson(xml);
In this piece of code, XML is generated using EmployeeToXml() method. In a
more realistic situation you will receive XML from some service or subsystem.
Converting from JSON to XML
The JsonToXml() method converts JSON version of Employee to XML version and
is shown below:
public static string JsonToXml(string jsonData)
{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
Employee emp = JsonSerializer.
Deserialize<Employee>(jsonData, options);
return EmployeeToXml(emp);
}
The JsonToXml() method accepts a string containing JSON representing an
Employee. It returns a string representing the data in XML format.
Inside, the code uses Deserializer() method of JsonSerializer to deserialize
JSON into an Employee object. The EmployeeToXml() method then converts the
Employee object into equivalent XML string.
A sample usage of JsonToXml() would look like this:
string json = JsonXmlHelper.EmployeeToJson(emp);
string xml2 = JsonXmlHelper.JsonToXml(json);
That's it for now! Keep coding!!