JSON & XML Handling in C#
C# provides built-in library support such as System.Text.Json for JSON, System.Xml.Serialization for XML handling, and various frameworks for serialization, de-serialization, and format conversion tasks.
Need of JSON & XML Handling in C#
In software development, data exchange between applications, servers, and devices is a necessity. Whether you are building a web API, mobile app, or desktop system, you need a common format to send and receive structured data.
Listed below are some of the important points regarding JSON and XML −
- Data Exchange between Systems − Both JSON and XML are widely used formats for transferring data between different applications, platforms, or devices. For example, a C# backend API can send JSON data to a JavaScript frontend. An XML-based configuration can be shared across multiple applications.
- Serialization and deserialization − In real-world applications, we often need to: Convert objects into a transmittable format (serialization) and Reconstruct objects from that format (de-serialization).
- Interoperability − A C# program can produce JSON/XML that can be understood by Java, Python, or any other language, ensuring smooth cross-platform data communication.
- Data Storage and Configuration − JSON is widely used in .NET applications for configuration files like "appsettings.json." Whereas, XML is used in legacy systems, configuration files, and document-based databases.
- Integration with Web Services and APIs − JSON is the standard format for most RESTful Web APIs. Whereas, XML remains widely used in SOAP-based services and enterprise-level applications.
Let's create a simple .NET console application named "JsonXmlExamples". This application explains the handling of JSON and XML. Its Folder Structure looks as follows −
Create the Project
Create the integrated terminal and run the following command one by one −
dotnet new console -n JsonXmlExamples cd JsonXmlExamples
Create the Folder Structure
mkdir Models mkdir Services mkdir Data
Define the Model
File: Models/Person.cs
using System;
namespace JsonXmlExamples.Models {
public class Person {
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
public override string ToString() {
return $"Name: {Name}, Age: {Age}, Email: {Email}";
}
}
}
JSON Handling
File: Services/JsonHandler.cs
To handle the "JSON," you will be using "System.Text.Json" to serialise and deserialise objects.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using JsonXmlExamples.Models;
namespace JsonXmlExamples.Services {
public static class JsonHandler {
private static readonly string filePath = "Data/person.json";
public static void SerializeToJson(Person person) {
string json = JsonSerializer.Serialize(person, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(filePath, json);
Console.WriteLine("\n JSON file created successfully!");
}
public static Person DeserializeFromJson()
{
if (!File.Exists(filePath))
{
Console.WriteLine("\n JSON file not found.");
return null;
}
string json = File.ReadAllText(filePath);
Person person = JsonSerializer.Deserialize<Person>(json);
Console.WriteLine("\n JSON deserialized successfully!");
return person;
}
public static void SerializeListToJson(List<Person> people) {
string json = JsonSerializer.Serialize(people, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText("Data/people.json", json);
Console.WriteLine("\n List of people saved to JSON!");
}
}
}
XML Handling
File: Services/XmlHandler.cs
To handle the "XML," you will be using "System.Xml.Serialization" for XML conversion.
using System;
using System.IO;
using System.Xml.Serialization;
using JsonXmlExamples.Models;
namespace JsonXmlExamples.Services {
public static class XmlHandler {
private static readonly string filePath = "Data/person.xml";
public static void SerializeToXml(Person person) {
XmlSerializer serializer = new XmlSerializer(typeof(Person));
using (TextWriter writer = new StreamWriter(filePath)) {
serializer.Serialize(writer, person);
}
Console.WriteLine("\n XML file created successfully!");
}
public static Person DeserializeFromXml() {
if (!File.Exists(filePath)) {
Console.WriteLine("\n XML file not found.");
return null;
}
XmlSerializer serializer = new XmlSerializer(typeof(Person));
using (TextReader reader = new StreamReader(filePath)) {
Person person = (Person)serializer.Deserialize(reader);
Console.WriteLine("\n XML deserialized successfully!");
return person;
}
}
}
}
Main Program
File: Program.cs
In C#, "Program.cs" is the main entry point of a .NET application where program execution start, simply it contains the Main() method that starts the application.
using System;
using System.Collections.Generic;
using JsonXmlExamples.Models;
using JsonXmlExamples.Services;
namespace JsonXmlExamples {
class Program {
static void Main(string[] args)
{
Console.WriteLine("JSON & XML Handling in C#");
Person person = new Person{
Name = "Amansha",
Age = 26,
Email = "amansha123@gmail.com"
};
// JSON Operations
JsonHandler.SerializeToJson(person);
var jsonPerson = JsonHandler.DeserializeFromJson();
Console.WriteLine($"\nFrom JSON â {jsonPerson}");
// XML Operations
XmlHandler.SerializeToXml(person);
var xmlPerson = XmlHandler.DeserializeFromXml();
Console.WriteLine($"\nFrom XML â {xmlPerson}");
// Serialize List to JSON
List<Person> people = new List<Person> {
new Person { Name = "Aman Kumar", Age = 26, Email = "amankumargupta8252@gmail.com" },
new Person { Name = "Akanksha Gupta", Age = 22, Email = "akankshagupta197@gmail.com" }
};
JsonHandler.SerializeListToJson(people);
}
}
}
Output
To execute the ".net" application, use this command: "dotnet run".
JSON & XML Handling in C# JSON file created successfully! JSON deserialized successfully! From JSON â Name: Amansha, Age: 26, Email: amansha123@gmail.com XML file created successfully! XML deserialized successfully! From XML â Name: Amansha, Age: 26, Email: amansha123@gmail.com
C# JSON vs XML
Following is the comparison table between JSON vs XML −
| Aspect | JSON Handling | XML Handling |
|---|---|---|
| Main API | System.Text.Json, Json.NET (Newtonsoft.Json) | System.Xml.Serialization, LINQ to XML |
| Serialize | JsonSerializer.Serialize, JsonConvert.SerializeObject | XmlSerializer.Serialize, XDocument.Save |
| Deserialize | JsonSerializer.Deserialize, JsonConvert.DeserializeObject | XmlSerializer.Deserialize, XElement.Parse |
| Conversion | JsonConvert.SerializeXmlNode/DeserializeXmlNode | XmlSerializer + JsonSerializer approach newtonsoft |
Conclusion
JSON and XML handling make data exchange, storage, and integration simple and efficient. With built-in libraries like "System.Text.Json" and "System.Xml.Serialization", developers can easily serialize, de-serialize, and manage data across applications for faster and smooth performance.