Created
September 5, 2021 13:23
-
-
Save 000407/cdc043724a79ebe711eb42ac225f2689 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.Text.Json; // Install this by using NuGet package manager | |
| namespace SerialisationDemo | |
| { | |
| class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| Student std1 = new Student(); | |
| std1.Name = "John Doe"; | |
| std1.Age = 25; | |
| std1.Hobbies = new List<string> { "music", "reading", "travelling" }; | |
| std1.Grades = new Dictionary<string, float> { { "math", 75 }, { "science", 73 }, { "english", 81 } }; | |
| // Serialisation: Convert C# object to a string representation (JSON) | |
| string serialisedStd1 = JsonSerializer.Serialize(std1); | |
| Console.WriteLine($"Student Object: {std1}"); | |
| Console.WriteLine($"Student Object Serialised: {serialisedStd1}"); | |
| Student deserialiserdStudent = JsonSerializer.Deserialize<Student>(serialisedStd1); | |
| Console.WriteLine($"std1 == deserialisedStudent: {std1.Equals(deserialiserdStudent)}"); | |
| Console.ReadLine(); | |
| } | |
| } | |
| class Student { | |
| public string Name { get; set; } | |
| public int Age { get; set; } | |
| public List<string> Hobbies { get; set; } | |
| public Dictionary<string, float> Grades { get; set; } | |
| public bool Equals(Student student) | |
| { | |
| if (!student.Name.Equals(Name)) | |
| { | |
| Console.WriteLine($"{student.Name} != {Name}"); | |
| return false; | |
| } | |
| if (student.Age != Age) | |
| { | |
| Console.WriteLine($"{student.Age} != {Age}"); | |
| return false; | |
| } | |
| return true; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment