ScholarQuill logoScholarQuillUniversity Notes
  • Notes
  • Past Papers
  • Blogs
  • Todo
Login
ScholarQuill logoScholarQuillUniversity Notes
Login
NotesPast PapersBlogsTodo
More
SubjectsDiscussionCGPA CalculatorGPA CalculatorStudent PortalCourse Outline
About
About usPrivacy PolicyReportContact
Notes
Past Papers
Blogs
Todo
Analytics
    Current Subject
    🧩
    Advanced Programming
    CSI-415
    Progress0 / 55 topics
    Topics
    1. Visual Programming Basics2. Introduction to Events3. Fundamentals of Event-Driven Programming4. Message Handling5. User Interfaces6. Graphics Device Interface7. Painting and Drawing8. Windows Management9. Input Devices10. Resources11. String and Menu Resource12. Dialogs and Windows Controls13. Common Controls14. Dynamic Link Libraries (DLLs)15. Threads and Synchronization16. Network Programming17. Building Class Libraries at the Command Line18. Class Libraries19. Using References20. Assemblies21. Private Assembly Deployment22. Shared Assembly Deployment23. Configuration Overview24. Configuration Files25. Programmatic Access to Configuration26. Using SDK Tools for Signing and Deployment27. Metadata28. Reflection29. Late Binding30. Directories and Files31. Serialization32. Attributes33. Memory Management and Garbage Collection34. Threading and Synchronization35. Asynchronous Delegates36. Application Domains37. Marshal by Value38. Marshal by Reference39. Authentication and Authorization40. Configuring Security41. Code Access Security42. Code Groups43. Evidence44. Permissions45. Role-Based Security46. Principals and Identities47. Using Data Readers48. Using Data Sets49. Interacting with XML Data50. Tracing Event Logs51. Using the Boolean Switch and Trace Switch Classes52. Print Debugging Information with the Debug Class53. Instrumenting Release Builds with the Trace Class54. Using Listeners55. Implementing Custom Listeners
    CSI-415›Serialization
    Advanced ProgrammingTopic 31 of 55

    Serialization

    8 minread
    1,278words
    Intermediatelevel

    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 load past papers

    Click on Show Past Papers to see past papers.
    On This Page
      Reading Stats
      Est. reading time8 min
      Word count1,278
      Code examples0
      DifficultyIntermediate