C# || Universal Object Serializer and Deserializer Using C#
The following is a module with functions which demonstrates how to create a simple universal object serializer and deserializer using C#.
The following functions take in a instance of the abstract classes ‘ObjectSerializer‘, and ‘ObjectDeserializer‘. Those classes defines the functionality that is common to all the classes derived from it. They are what carries out the actual serialization and deserialization.
Breaking things up like so makes it easy to have different serializations with only calling one function.
Note: The functions in this module uses code from previous articles which explains how to serialize and deserialize objects.
For those examples of how to serialize and deserialize objects using Json and XML, see below:
1. JsonSerializer
The example below demonstrates the use of ‘Utils.Objects.JsonSerializer‘ to serialize an object to Json.
By changing the second parameter, calling the same function will change its behavior.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
// JsonSerializer public class Part { public string PartName { get; set; } public int PartId { get; set; } } // Declare list of objects var parts = new List<Part>() { new Part() { PartName = "crank arm", PartId = 1234 }, new Part() { PartName = "chain ring", PartId = 1334 }, new Part() { PartName = "regular seat", PartId = 1434 }, new Part() { PartName = "banana seat", PartId = 1444 }, new Part() { PartName = "cassette", PartId = 1534 }, new Part() { PartName = "shift lever", PartId = 1634 } }; // Serialize to json var serialized = Utils.Objects.Serialize(parts, new Utils.Objects.JsonSerializer()); // Display json Console.WriteLine(serialized); // expected output: /* [ { "PartName": "crank arm", "PartId": 1234 }, { "PartName": "chain ring", "PartId": 1334 }, { "PartName": "regular seat", "PartId": 1434 }, { "PartName": "banana seat", "PartId": 1444 }, { "PartName": "cassette", "PartId": 1534 }, { "PartName": "shift lever", "PartId": 1634 } ] */ |
2. JsonDeserializer
The example below demonstrates the use of ‘Utils.Objects.JsonDeserializer‘ to deserialize an object from Json.
By changing the second parameter, calling the same function will change its behavior.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
// JsonDeserializer // Declare Json array of objects var partsJson = @" [ { ""PartName"": ""crank arm"", ""PartId"": 1234 }, { ""PartName"": ""chain ring"", ""PartId"": 1334 }, { ""PartName"": ""regular seat"", ""PartId"": 1434 }, { ""PartName"": ""banana seat"", ""PartId"": 1444 }, { ""PartName"": ""cassette"", ""PartId"": 1534 }, { ""PartName"": ""shift lever"", ""PartId"": 1634 } ] "; // Deserialize to object var deserialized = Utils.Objects.Deserialize<List<Part>>(partsJson, new Utils.Objects.JsonDeserializer()); // Display the items foreach (var item in deserialized) { Console.WriteLine($"{item.PartId} - {item.PartName}"); } // expected output: /* 1234 - crank arm 1334 - chain ring 1434 - regular seat 1444 - banana seat 1534 - cassette 1634 - shift lever */ |
3. XmlSerializer
The example below demonstrates the use of ‘Utils.Objects.XmlSerializer‘ to serialize an object to Xml.
By changing the second parameter, calling the same function will change its behavior.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
// XmlSerializer public class Part { public string PartName { get; set; } public int PartId { get; set; } } // Declare list of objects var parts = new List<Part>() { new Part() { PartName = "crank arm", PartId = 1234 }, new Part() { PartName = "chain ring", PartId = 1334 }, new Part() { PartName = "regular seat", PartId = 1434 }, new Part() { PartName = "banana seat", PartId = 1444 }, new Part() { PartName = "cassette", PartId = 1534 }, new Part() { PartName = "shift lever", PartId = 1634 } }; // Serialize to xml var serialized2 = Utils.Objects.Serialize(parts, new Utils.Objects.XmlSerializer()); // Display xml Console.WriteLine(serialized2); // expected output: /* <?xml version="1.0"?> <ArrayOfPart xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Part> <PartName>crank arm</PartName> <PartId>1234</PartId> </Part> <Part> <PartName>chain ring</PartName> <PartId>1334</PartId> </Part> <Part> <PartName>regular seat</PartName> <PartId>1434</PartId> </Part> <Part> <PartName>banana seat</PartName> <PartId>1444</PartId> </Part> <Part> <PartName>cassette</PartName> <PartId>1534</PartId> </Part> <Part> <PartName>shift lever</PartName> <PartId>1634</PartId> </Part> </ArrayOfPart> */ |
4. XmlDeserializer
The example below demonstrates the use of ‘Utils.Objects.XmlDeserializer‘ to deserialize an object from xml.
By changing the second parameter, calling the same function will change its behavior.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
// XmlDeserializer // Declare Xml array of objects var partsXml = $@"<?xml version=""1.0""?> <ArrayOfPart xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <Part> <PartName>crank arm</PartName> <PartId>1234</PartId> </Part> <Part> <PartName>chain ring</PartName> <PartId>1334</PartId> </Part> <Part> <PartName>regular seat</PartName> <PartId>1434</PartId> </Part> <Part> <PartName>banana seat</PartName> <PartId>1444</PartId> </Part> <Part> <PartName>cassette</PartName> <PartId>1534</PartId> </Part> <Part> <PartName>shift lever</PartName> <PartId>1634</PartId> </Part> </ArrayOfPart> "; // Deserialize to object var deserialized2 = Utils.Objects.Deserialize<List<Part>>(partsXml, new Utils.Objects.XmlDeserializer()); // Display the items foreach (var item in deserialized2) { Console.WriteLine($"{item.PartId} - {item.PartName}"); } // expected output: /* 1234 - crank arm 1334 - chain ring 1434 - regular seat 1444 - banana seat 1534 - cassette 1634 - shift lever */ |
5. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 11, 2021 // Taken From: http://programmingnotes.org/ // File: Utils.cs // Description: Handles general utility functions // ============================================================================ using System; namespace Utils { public static class Objects { /// <summary> /// Serializes the specified value according to the ObjectSerializer /// </summary> /// <param name="value">The value to serialize</param> /// <param name="serializer">Determines how the value should be serialized</param> /// <returns>The value serialized according to the ObjectSerializer</returns> public static string Serialize<T>(T value, ObjectSerializer serializer) { return serializer.Serialize(value); } /// <summary> /// Deserializes the specified value according to the ObjectDeserializer /// </summary> /// <param name="value">The value to deserialize</param> /// <param name="deserializer">Determines how the value should be deserialized</param> /// <returns>The value deserialized according to the ObjectSerializer</returns> public static T Deserialize<T>(string value, ObjectDeserializer deserializer) { return deserializer.Deserialize<T>(value); } #region "ObjectSerializer" /// <summary> /// Defines the object serializer behavior /// </summary> public abstract class ObjectSerializer { public abstract string Serialize<T>(T value); } public class JsonSerializer : ObjectSerializer { public Newtonsoft.Json.JsonSerializerSettings settings { get; set; } = new Newtonsoft.Json.JsonSerializerSettings(); public JsonSerializer() { settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; settings.Formatting = Newtonsoft.Json.Formatting.Indented; } public override string Serialize<T>(T value) { return Utils.Json.Serialize(value, settings); } } public class XmlSerializer : ObjectSerializer { public System.Xml.Serialization.XmlRootAttribute root { get; set; } = new System.Xml.Serialization.XmlRootAttribute(); public override string Serialize<T>(T value) { return Utils.Xml.Serialize(value, root); } } #endregion #region "ObjectDeserializer" /// <summary> /// Defines the object deserializer behavior /// </summary> public abstract class ObjectDeserializer { public abstract T Deserialize<T>(string value); } public class JsonDeserializer : ObjectDeserializer { public Newtonsoft.Json.JsonSerializerSettings settings { get; set; } = new Newtonsoft.Json.JsonSerializerSettings(); public JsonDeserializer() { settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; } public override T Deserialize<T>(string value) { T obj = default; if (!string.IsNullOrEmpty(value)) { obj = Utils.Json.Deserialize<T>(value, settings); } return obj; } } public class XmlDeserializer : ObjectDeserializer { public System.Xml.Serialization.XmlRootAttribute root { get; set; } = new System.Xml.Serialization.XmlRootAttribute(); public override T Deserialize<T>(string value) { T obj = default; if (!string.IsNullOrEmpty(value)) { obj = Utils.Xml.Deserialize<T>(value, root); } return obj; } } #endregion } }// http://programmingnotes.org/ |
6. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
// ============================================================================ // Author: Kenneth Perkins // Date: May 11, 2021 // Taken From: http://programmingnotes.org/ // File: Program.cs // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ using System; using System.Diagnostics; using System.Collections.Generic; public class Program { public class Part { public string PartName { get; set; } public int PartId { get; set; } } static void Main(string[] args) { try { // Declare list of objects var parts = new List<Part>() { new Part() { PartName = "crank arm", PartId = 1234 }, new Part() { PartName = "chain ring", PartId = 1334 }, new Part() { PartName = "regular seat", PartId = 1434 }, new Part() { PartName = "banana seat", PartId = 1444 }, new Part() { PartName = "cassette", PartId = 1534 }, new Part() { PartName = "shift lever", PartId = 1634 } }; // Serialize to json var serialized = Utils.Objects.Serialize(parts, new Utils.Objects.JsonSerializer()); // Display json Display(serialized); // Declare Json array of objects var partsJson = @" [ { ""PartName"": ""crank arm"", ""PartId"": 1234 }, { ""PartName"": ""chain ring"", ""PartId"": 1334 }, { ""PartName"": ""regular seat"", ""PartId"": 1434 }, { ""PartName"": ""banana seat"", ""PartId"": 1444 }, { ""PartName"": ""cassette"", ""PartId"": 1534 }, { ""PartName"": ""shift lever"", ""PartId"": 1634 } ] "; // Deserialize to object var deserialized = Utils.Objects.Deserialize<List<Part>>(partsJson, new Utils.Objects.JsonDeserializer()); // Display the items foreach (var item in deserialized) { Display($"{item.PartId} - {item.PartName}"); } Display(""); // Serialize to xml var serialized2 = Utils.Objects.Serialize(parts, new Utils.Objects.XmlSerializer()); // Display xml Display(serialized2); // Declare Xml array of objects var partsXml = $@"<?xml version=""1.0""?> <ArrayOfPart xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""> <Part> <PartName>crank arm</PartName> <PartId>1234</PartId> </Part> <Part> <PartName>chain ring</PartName> <PartId>1334</PartId> </Part> <Part> <PartName>regular seat</PartName> <PartId>1434</PartId> </Part> <Part> <PartName>banana seat</PartName> <PartId>1444</PartId> </Part> <Part> <PartName>cassette</PartName> <PartId>1534</PartId> </Part> <Part> <PartName>shift lever</PartName> <PartId>1634</PartId> </Part> </ArrayOfPart> "; // Deserialize to object var deserialized2 = Utils.Objects.Deserialize<List<Part>>(partsXml, new Utils.Objects.XmlDeserializer()); // Display the items foreach (var item in deserialized2) { Display($"{item.PartId} - {item.PartName}"); } } catch (Exception ex) { Display(ex.ToString()); } finally { Console.ReadLine(); } } static void Display(string message) { Console.WriteLine(message); Debug.Print(message); } }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Leave a Reply