Skip to main content

Command Palette

Search for a command to run...

Day 30 of 30-Day .NET Challenge: XML v/s JSON Serialization

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

Published
2 min read
Day 30 of 30-Day .NET Challenge: XML v/s JSON Serialization
S

Hi there 👋 I'm Sukhpinder Singh, a passionate self-taught .Net developer from India. Worked on 10+ projects for SQL database design. Developed and maintained over 20 .NET websites with 100% client satisfaction.

Skills C# | Microsoft Certified | Medium Blogger | .Net Core | Xamarin | ASP.Net | Angular


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

Getting Started

Drawbacks of XML Serialization

Traditionally many developers have used XML Serialization as demonstrated in the following code snippet.

// 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

// 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

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

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Execute from the main method as follows

#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

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


C# Programming🚀

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

Follow us: Youtube | X | LinkedIn | Dev.to
Visit our other platforms: GitHub
More content at C# Programming

30 Day C# Challenge

Part 1 of 30

The series consists of a 30-day code challenge where I'll be diving deep into a different C# concept every single day. 🌟 I'll also be sharing my learnings and insights through engaging articles.

Up next

Day 29 of 30-Day .NET Challenge: Generics & Custom Interfaces

Learn to enhance your maintainability with generics and custom interfaces in C#. Discover a better approach on Day 29 of our 30-Day .NET Challenge.