How to work with XML and JSON in .NET?


Working with JSON

JSON is a data format that has become a popular alternative to XML. It is simple and uncluttered with a syntax similar to a JavaScript object. In fact, the term JSON stands for JavaScript Object Notation. The recent versions of .NET provide built-in support for working with JSON data.

The System.Text.Json namespace provides high-performance, low-allocating features to process the JSON data. These features include serializing objects to JSON and deserializing JSON back into objects. It also provides types to create an in-memory document object model (DOM) for accessing any element within the JSON document, providing a structured view of the data.

Serializing JSON

Let's say you have a class Point that has two properties, X and Y as follows.

class Point{
   public int X { get; set; }

   public int Y { get; set; }
}

To serialize an instance of Point class, you'll use the Serialize() method defined on the JsonSerializer class, which is found in the System.Text.Json namespace.

var point = new Point { X = 10, Y = 20 };
string jsonString = JsonSerializer.Serialize(point);
Console.WriteLine(jsonString); // {"X":10,"Y":20}

To print the json data with proper formatting and indentation, you can pass the JsonSerializerOptions to the Serializer method, specifying the WriteIndented property to true.

string formattedString = JsonSerializer.Serialize(point, new JsonSerializerOptions { WriteIndented = true });
Console.WriteLine(formattedString);

Deserializing from JSON

To deserialize from a JSON data to C# objects, you can use the generic Deserialize<T> method on the JSONSerializer class. For example,

string jsonData = "{\"X\":10,\"Y\":20}";
Point q = JsonSerializer.Deserialize<Point>(jsonData);
Console.WriteLine(q.X + " " + q.Y); // prints 10 20

Working with XML

XML is a very popular data format to store and transfer data. .NET provides a number of APIs to work with XML in the C# programming language. Linq to XML is the primary mechanism for general-purpose XML processing. It provides a lightweight, linq-friendly XML document object model along with a set of query operators. System.XML.Linq namespace contains the types related to Linq to XML.

Consider the following XML data. It has a root element, employee with two attributes id and status with the values '231' and 'active' respectively. The element has three child elements: firstname, lastname, and salary.

<?xml version="1.0" encoding="utf-8"?>
<employee id="231" status="active">
<firstname>David</firstname>
<lastname>Block</lastname>
<salary>45000</salary>
</employee>

The Linq to XML API parses XML data and represents each element, attribute, value, and content as objects with properties to store related data. It forms a tree of objects which fully represents the document and this tree is called the DOM which stands for Document Object Model.

XElement and XDocument provide static Load and Parse methods to build the document object model from an XML data source. Load builds the DOM from a file, stream, URL, TextReader, and XmlReader; whereas Parse builds the DOM from a string.

string path = Path.Combine("Data", "data.xml");
string xmlData = File.ReadAllText(path);

XElement employee = XElement.Parse(xmlData);

The Elements() method provides all the children of an element. For example −

foreach (var elem in employee.Elements()){
   Console.WriteLine(elem.Name);
}

ToString() method on an element returns the XML string with the line breaks and proper formatting. For example −

Console.Write(employee.ToString());
/* Prints
<employee id="123" status="active">
   <firstname>David</firstname>
   <lastname>Block</lastname>
   <salary>45000</salary>
</employee>%
*/

Example

Note: The JSON library is only included in .NET Core. For earlier versions, a Nuget package must be imported.

using System;
using System.Text.Json;
class Program{
   static void Main(string[] args){
      var point = new Point { X = 10, Y = 20 };
      string jsonString = JsonSerializer.Serialize(point);
      Console.WriteLine(jsonString); // {"X":10,"Y":20}
      string formattedString = JsonSerializer.Serialize(point, new JsonSerializerOptions {       WriteIndented = true });
      Console.WriteLine(formattedString);
      string jsonData = "{\"X\":10,\"Y\":20}";
      Point q = JsonSerializer.Deserialize<Point>(jsonData);
      Console.WriteLine(q.X + " " + q.Y); // prints 10 20
   }
}
class Point{
   public int X { get; set; }
   public int Y { get; set; }
}

Output

{"X":10,"Y":20}{
   "X": 10,
   "Y": 20
}
10 20

Updated on: 19-May-2021

790 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements