Keywords: C# | JSON | XML | Json.NET | Data Conversion
Abstract: This article provides an in-depth exploration of JSON and XML format conversion techniques in C# using the Json.NET library. Through detailed code examples and performance analysis, it covers essential functionalities including basic conversion methods, formatting options, root element handling, and array conversion. The article also compares the advantages and disadvantages of Newtonsoft.Json and System.Text.Json approaches, offering best practices and considerations for real-world application scenarios.
Introduction
In modern software development, JSON and XML serve as two primary data interchange formats that frequently require mutual conversion between different systems. As a key language for enterprise application development, C# offers multiple technical solutions for implementing this functionality. This article systematically introduces the core technologies for JSON and XML mutual conversion based on the Json.NET framework.
Json.NET Conversion Fundamentals
Json.NET (Newtonsoft.Json) is the most popular JSON processing library in the .NET ecosystem, providing comprehensive JSON and XML conversion capabilities. Its core conversion methods are encapsulated in the JsonConvert class, offering simplicity and powerful functionality.
Basic XML to JSON Implementation
The fundamental method for converting XML documents to JSON strings is as follows:
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
This method accepts an XML string as input, loads it via XmlDocument, and uses the SerializeXmlNode method to generate the corresponding JSON format string.
Basic JSON to XML Implementation
The reverse conversion is equally straightforward:
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);
This method directly parses the JSON string into an XmlDocument object, preserving the complete structure of the XML document.
Advanced Conversion Features
Formatting Output Control
To improve readability, Json.NET supports formatting output options:
var doc = XDocument.Parse(xml);
string prettyJson = JsonConvert.SerializeXNode(doc, Formatting.Indented);
Using the Formatting.Indented parameter generates formatted JSON with indentation, though this increases output size and impacts performance.
Root Element Handling Strategies
For scenarios requiring removal of wrapper root elements, use the omitRootObject parameter:
string jsonWithoutRoot = JsonConvert.SerializeXNode(doc, Formatting.None, omitRootObject: true);
This feature is particularly useful for processing XML data containing redundant wrapper elements, though compatibility issues may arise when XML declarations are present.
Array Element Forced Conversion
When the number of repeating elements in XML is uncertain, ensure array consistency by adding JSON namespace:
var xmlWithArray = @"<?xml version='1.0'?>
<SquidGame xmlns:json='http://james.newtonking.com/projects/json'>
<Stars json:Array='true'>Lee Jung-jae</Stars>
</SquidGame>";
Alternatively, dynamically add array markers programmatically:
var doc = XDocument.Parse(xml);
var jsonNamespace = "http://james.newtonking.com/projects/json";
doc.Root.Add(new XAttribute(XNamespace.Xmlns + "json", jsonNamespace));
elements.Single().Add(new XAttribute(XNamespace.Get(jsonNamespace) + "Array", true));
Conversion Rules Detailed Explanation
Json.NET follows specific mapping rules during conversion:
- XML declarations (
<?xml ... ?>) are represented with "?" prefix in JSON - XML attributes are identified with "@" prefix when converted to JSON
- Text nodes containing attributes use "#text" key to store content
- Repeating elements with the same name are automatically merged into JSON arrays
- Empty elements are converted to
nullvalues - Numeric types are converted to string format by default
System.Text.Json Alternative Approach
Although the native System.Text.Json library doesn't directly support JSON-XML conversion, it can be achieved through intermediate POCO objects:
JSON to XML Implementation
public static string JsonToXml(string json)
{
var obj = JsonSerializer.Deserialize<RootObject>(json);
return ObjectToXml(obj.SquidGame);
}
static string ObjectToXml<T>(T obj)
{
var xmlSerializer = new XmlSerializer(typeof(T));
var sb = new StringBuilder();
using var xmlWriter = XmlWriter.Create(sb);
var ns = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });
xmlSerializer.Serialize(xmlWriter, obj, ns);
return sb.ToString();
}
XML to JSON Implementation
public static string XmlToJson(string xml)
{
var obj = XmlToObject<SquidGame>(xml);
return JsonSerializer.Serialize(new RootObject { SquidGame = obj });
}
static T XmlToObject<T>(string xml)
{
var xmlSerializer = new XmlSerializer(typeof(T));
using var stringReader = new StringReader(xml);
return (T)xmlSerializer.Deserialize(stringReader);
}
Performance Comparison Analysis
Benchmark tests reveal significant performance differences between the two approaches:
- JSON to XML: Newtonsoft.Json (6.465 μs) is approximately 27% faster than System.Text.Json (8.898 μs)
- XML to JSON: Newtonsoft.Json (7.705 μs) is approximately 49% faster than System.Text.Json (15.053 μs)
Newtonsoft.Json demonstrates clear performance advantages over the native solution, particularly in XML to JSON conversion scenarios.
Practical Application Recommendations
When selecting a conversion approach, consider the following factors:
- Performance Requirements: Prefer Newtonsoft.Json for performance-sensitive scenarios
- Dependency Management: Consider System.Text.Json approach when minimizing third-party dependencies
- Data Structure Complexity: Complex nested structures are better suited for Newtonsoft.Json's direct conversion
- Formatting Needs: Newtonsoft.Json offers more options for fine-grained output format control
Conclusion
Json.NET provides C# developers with powerful and efficient JSON and XML conversion capabilities. Its intuitive API design, rich configuration options, and excellent performance make it the preferred solution for data format conversion tasks. Although System.Text.Json offers a native alternative, it still lags behind in conversion functionality and performance. Developers should choose the most suitable conversion strategy based on specific project requirements and technical constraints.