ScholarQuill logoScholarQuillUniversity Notes
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
Study Tools
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
Contact
ScholarQuill logo
My Semester
Explore Notes
Past Papers12 New
Video CoursesNew
Search
Settings
GPA/CGPA Calculator
Schedule & To-Do
Student Portal
Contact
ScholarQuill logoScholarQuillUniversity Notes
Study PortalCSI-415Serialization
Ctrl + K
Login
Explore
Search
Semester
Papers
CGPA
    CSI-415

    Advanced Programming

    Progress0 / 55 done
    Topics55
    1Visual Programming Basics2Introduction to Events3Fundamentals of Event-Driven Programming4Message Handling5User Interfaces6Graphics Device Interface7Painting and Drawing8Windows Management9Input Devices10Resources11String and Menu Resource12Dialogs and Windows Controls13Common Controls14Dynamic Link Libraries (DLLs)15Threads and Synchronization16Network Programming17Building Class Libraries at the Command Line18Class Libraries19Using References20Assemblies21Private Assembly Deployment22Shared Assembly Deployment23Configuration Overview24Configuration Files25Programmatic Access to Configuration26Using SDK Tools for Signing and Deployment27Metadata28Reflection29Late Binding30Directories and Files31Serialization32Attributes33Memory Management and Garbage Collection34Threading and Synchronization35Asynchronous Delegates36Application Domains37Marshal by Value38Marshal by Reference39Authentication and Authorization40Configuring Security41Code Access Security42Code Groups43Evidence44Permissions45Role-Based Security46Principals and Identities47Using Data Readers48Using Data Sets49Interacting with XML Data50Tracing Event Logs51Using the Boolean Switch and Trace Switch Classes52Print Debugging Information with the Debug Class53Instrumenting Release Builds with the Trace Class54Using Listeners55Implementing Custom Listeners
    8 min read
    Topic 31 of 55
    Topic Study Note Illustration
    31

    Serialization

    Serialization is the process of converting an object into a format that can be easily stored (such as in a file or database) or transmitted (over a...

    Serialization in .NET

    Serialization is the process of converting an object into a format that can be easily stored (such as in a file or database) or transmitted (over a network). The reverse process, where serialized data is transformed back into an object, is called deserialization.

    In .NET, serialization is supported through different techniques, and it plays a critical role in scenarios like saving the state of an object, communication between different components of an application, and working with distributed systems.

    Types of Serialization

    1. Binary Serialization
    2. XML Serialization
    3. JSON Serialization
    4. Custom Serialization

    Each serialization type is used depending on the format and needs of the application.


    1. Binary Serialization

    Binary Serialization converts an object into a binary format, making it compact and efficient for storage or transmission. This format is not human-readable and is used when performance is a priority, especially in scenarios where the object will only be deserialized within the same application.

    • Requires: The object to be serialized must be marked with the [Serializable] attribute.

    Example of Binary Serialization

    using System;
    using System.IO;
    using System.Runtime.Serialization.Formatters.Binary;
    
    [Serializable]
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            Person person = new Person { Name = "John Doe", Age = 30 };
    
            // Serialize the object to a file
            using (FileStream stream = new FileStream("person.dat", FileMode.Create))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, person);
                Console.WriteLine("Object serialized to person.dat.");
            }
    
            // Deserialize the object from the file
            using (FileStream stream = new FileStream("person.dat", FileMode.Open))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                Person deserializedPerson = (Person)formatter.Deserialize(stream);
                Console.WriteLine($"Deserialized object: {deserializedPerson.Name}, {deserializedPerson.Age} years old.");
            }
        }
    }
    

    In this example, the Person object is serialized into a binary file and later deserialized back into an object.


    2. XML Serialization

    XML Serialization converts an object into an XML format. This format is human-readable, widely used, and can be transmitted easily across different systems or platforms. XML serialization is useful for web services, configuration files, or storing data in a structured, readable format.

    • Requires: The object to be serialized must have public properties or fields and can optionally be marked with the [XmlElement] attribute for custom mapping.

    Example of XML Serialization

    using System;
    using System.IO;
    using System.Xml.Serialization;
    
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            Person person = new Person { Name = "John Doe", Age = 30 };
    
            // Serialize the object to XML format
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(Person));
            using (StreamWriter writer = new StreamWriter("person.xml"))
            {
                xmlSerializer.Serialize(writer, person);
                Console.WriteLine("Object serialized to person.xml.");
            }
    
            // Deserialize the object from the XML file
            using (StreamReader reader = new StreamReader("person.xml"))
            {
                Person deserializedPerson = (Person)xmlSerializer.Deserialize(reader);
                Console.WriteLine($"Deserialized object: {deserializedPerson.Name}, {deserializedPerson.Age} years old.");
            }
        }
    }
    

    In this example, the Person object is serialized into an XML file and later deserialized back into an object.


    3. JSON Serialization

    JSON Serialization converts an object into a JSON format, which is lightweight, easy to read, and commonly used in web services, APIs, and web applications. JSON is platform-independent, making it ideal for exchanging data between systems built with different technologies.

    • Requires: The object can be serialized with the help of libraries like Newtonsoft.Json (a popular third-party library) or the built-in System.Text.Json (in .NET Core and later).

    Example of JSON Serialization (Using System.Text.Json)

    using System;
    using System.IO;
    using System.Text.Json;
    
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            Person person = new Person { Name = "John Doe", Age = 30 };
    
            // Serialize the object to JSON format
            string jsonString = JsonSerializer.Serialize(person);
            File.WriteAllText("person.json", jsonString);
            Console.WriteLine("Object serialized to person.json.");
    
            // Deserialize the object from JSON
            string jsonStringFromFile = File.ReadAllText("person.json");
            Person deserializedPerson = JsonSerializer.Deserialize<Person>(jsonStringFromFile);
            Console.WriteLine($"Deserialized object: {deserializedPerson.Name}, {deserializedPerson.Age} years old.");
        }
    }
    

    Example of JSON Serialization (Using Newtonsoft.Json)

    using System;
    using Newtonsoft.Json;
    using System.IO;
    
    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            Person person = new Person { Name = "John Doe", Age = 30 };
    
            // Serialize the object to JSON format using Newtonsoft.Json
            string jsonString = JsonConvert.SerializeObject(person);
            File.WriteAllText("person.json", jsonString);
            Console.WriteLine("Object serialized to person.json.");
    
            // Deserialize the object from JSON
            string jsonStringFromFile = File.ReadAllText("person.json");
            Person deserializedPerson = JsonConvert.DeserializeObject<Person>(jsonStringFromFile);
            Console.WriteLine($"Deserialized object: {deserializedPerson.Name}, {deserializedPerson.Age} years old.");
        }
    }
    

    Both System.Text.Json and Newtonsoft.Json offer similar functionality for JSON serialization and deserialization, with Newtonsoft.Json providing more features and flexibility, and System.Text.Json being faster and more lightweight.


    4. Custom Serialization

    In some cases, you may need to control how an object is serialized or deserialized, such as excluding certain fields or performing custom processing. This is where Custom Serialization comes into play.

    .NET provides mechanisms to implement custom serialization logic using interfaces like ISerializable and attributes like [OnSerializing], [OnDeserialized], etc.

    Example of Custom Serialization with ISerializable

    using System;
    using System.IO;
    using System.Runtime.Serialization;
    
    [Serializable]
    public class Person : ISerializable
    {
        public string Name { get; set; }
        public int Age { get; set; }
    
        // Custom serialization constructor
        public Person(SerializationInfo info, StreamingContext context)
        {
            Name = info.GetString("Name");
            Age = info.GetInt32("Age");
        }
    
        // Implement GetObjectData to control how the object is serialized
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("Name", Name);
            info.AddValue("Age", Age);
        }
    }
    
    class Program
    {
        static void Main()
        {
            Person person = new Person { Name = "John Doe", Age = 30 };
    
            // Serialize the object to a file with custom serialization
            using (FileStream stream = new FileStream("person_custom.dat", FileMode.Create))
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(stream, person);
                Console.WriteLine("Object serialized with custom serialization.");
            }
    
            // Deserialize the object from the file
            using (FileStream stream = new FileStream("person_custom.dat", FileMode.Open))
            {
                IFormatter formatter = new BinaryFormatter();
                Person deserializedPerson = (Person)formatter.Deserialize(stream);
                Console.WriteLine($"Deserialized object: {deserializedPerson.Name}, {deserializedPerson.Age} years old.");
            }
        }
    }
    

    In this example, the Person class implements ISerializable, providing custom logic for serialization and deserialization through the GetObjectData and the constructor that takes SerializationInfo.


    Serialization vs. Deserialization

    • Serialization: The process of converting an object into a format that can be stored or transmitted (e.g., binary, XML, JSON).
    • Deserialization: The reverse process of converting serialized data back into an object.

    Serialization is useful in scenarios like:

    • Persisting data (e.g., saving user settings or application state).
    • Interfacing with web services (e.g., exchanging data between a server and client using XML or JSON).
    • Deep cloning objects.

    Key Considerations

    • Versioning: When the structure of a serialized object changes (e.g., adding/removing properties), deserialization might fail unless backward compatibility is maintained.
    • Security: Deserialization, especially from untrusted sources, can expose applications to security risks, such as object injection attacks. Always validate and sanitize data before deserialization.

    Summary

    • Serialization is the process of converting objects into a format suitable for storage or transmission, such as binary, XML, or JSON.
    • Different types of serialization are available in .NET, including binary, XML, and JSON serialization.
    • Custom serialization allows you to control how objects are serialized and deserialized
    ← Previous topic 30
    Directories and Files
    Next topic 32 →
    Attributes

    Past Papers

    Open this section to view and download past papers

    Click on Show Past Papers to load available exam papers.

    Reading Progress
    0%
    8mremaining
    1.3kwords
    Intermediatelevel
    On This Page

    No headings found

    Study Toolkit

    Subject Portal

    Advanced Programming