Day 30 of 30-Day .NET Challenge: XML v/s JSON Serialization
Tags: dotnet, csharp, programming, beginners
Published: 2024-04-20 05:52:00

Learn to enhance your code with JSON Serialization in C#. Discover a better approach on Day 30 of our 30-Day .NET Challenge.

## Introduction

Serialization involves a process of converting an object into an easily stored format. The article demonstrates the problem with old XML Serialization and how JSON serialization improves both efficiency and effectiveness. 

### Learning Objectives

* Drawbacks of XML Serialization

* Advantages of JSON Serialization

### Prerequisites for Developers

* Basic understanding of C# programming language.

[30 Day .Net Challenge](https://singhsukhpinder.medium.com/list/52a751260fe1)

## Getting Started

### Drawbacks of XML Serialization

Traditionally many developers have used XML Serialization as demonstrated in the following code snippet.
```csharp
    // Using XmlSerializer for data serialization
    private string SerializeObjectToXml<T>(T obj)
    {
        var serializer = new XmlSerializer(typeof(T));
        using (var writer = new StringWriter())
        {
            serializer.Serialize(writer, obj);
            return writer.ToString();
        }
    }
```
Even though XML is human-readable and globally supported it is not an optimized and efficient choice of serialization in the C# programming language. The main reason is that it involves a lot of temporary objects which can impact the memory usage and the corresponding GC pressure.

### Advantages of JSON Serialization

Please find below the refactored version of the previous code snippet using NewtonSoft.Json library
```csharp
    // Using Newtonsoft.Json for data serialization
    private string SerializeObjectToJson<T>(T obj)
    {
        return JsonConvert.SerializeObject(obj);
    }
```
The aforementioned library outperforms XmlSerializer in both speed and efficiency. In addition to that, the JSON files are smaller in size which makes reading and writing faster.

## Complete Code

Create another class named EfficientSerialization and add the following code snippet
```csharp
    public static class EfficientSerialization
    {
        public static string XML<T>(T obj)
        {
    
            var serializer = new XmlSerializer(typeof(T));
            using (var writer = new StringWriter())
            {
                serializer.Serialize(writer, obj);
                return writer.ToString();
            }
        }
        public static string JSON<T>(T obj)
        {
            return JsonConvert.SerializeObject(obj);
        }
    }
```
And create a model class as follows
```csharp
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
```
## Execute from the main method as follows
```csharp
    #region Day 30: Efficient Serialization
    static string ExecuteDay30()
    {
        Person person = new Person { Name = "John Doe", Age = 30 };
    
        // XML Serialization
        string xmlData = EfficientSerialization.XML(person);
        Console.WriteLine("XML Serialization Output:");
        Console.WriteLine(xmlData);
    
        // JSON Serialization
        string jsonData = EfficientSerialization.JSON(person);
        Console.WriteLine("JSON Serialization Output:");
        Console.WriteLine(jsonData);
    
        return "Executed Day 30 successfully..!!";
    }
    
    #endregion
```
## Console Output
```csharp
    XML Serialization Output:
    <?xml version="1.0" encoding="utf-16"?>
    <Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      <Name>John Doe</Name>
      <Age>30</Age>
    </Person>
    
    JSON Serialization Output:
    {"Name":"John Doe","Age":30}
```
## Complete Code on GitHub
[GitHub — ssukhpinder/30DayChallenge.Net](https://github.com/ssukhpinder/30DayChallenge.Net/tree/main)

### C# Programming🚀

Thank you for being a part of the C# community! Before you leave:

Follow us: [Youtube](https://www.youtube.com/channel/UCejYGg4gAOa1uPAObFuk1HQ) | [X](https://twitter.com/sukhsukhpinder) | [LinkedIn](https://www.linkedin.com/in/sukhpinder-singh/) | [Dev.to](https://dev.to/ssukhpinder) 
Visit our other platforms: [GitHub](https://github.com/ssukhpinder) 
More content at [C# Programming](https://medium.com/c-sharp-progarmming)