Last active
November 12, 2025 11:39
-
-
Save sunmeat/857e8973436a90f6033ad5e520d32243 to your computer and use it in GitHub Desktop.
JSON serialization C# example
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.Text.Json; | |
| using System.Text.Json.Serialization; | |
| using System.Text.Encodings.Web; | |
| namespace JSONSerializerExample | |
| { | |
| public class Human | |
| { | |
| public string? Name { get; set; } | |
| [JsonIgnore] | |
| public int Age { get; set; } | |
| } | |
| public class SuperHero : Human | |
| { | |
| public bool IsEvil { get; set; } | |
| public Ability Superpower { get; set; } = new Ability(); | |
| } | |
| public class Ability | |
| { | |
| public bool IsUnique { get; set; } | |
| public string[]? Abilities { get; set; } | |
| } | |
| class Program | |
| { | |
| static void Main() | |
| { | |
| System.Console.OutputEncoding = System.Text.Encoding.UTF8; | |
| string filePath = "test.json"; | |
| var hero = new SuperHero(); | |
| hero.Name = "Хронічний Рефлюкс"; | |
| hero.Age = 36; | |
| hero.IsEvil = false; | |
| hero.Superpower.Abilities = new string[] { "гострий зір", | |
| "невидимість", "телекинез", "генерація кислоти", | |
| "телепортація", "воскресіння", "маніпуляція часом" }; | |
| hero.Superpower.IsUnique = true; | |
| var options = new JsonSerializerOptions | |
| { | |
| WriteIndented = true, | |
| Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping // для кирилиці в файлі | |
| }; | |
| // створює новий потік файлу для запису серіалізованого об'єкта у json файл | |
| var write = new FileStream(filePath, FileMode.Create, FileAccess.Write); | |
| JsonSerializer.Serialize(write, hero, options); | |
| write.Close(); | |
| // створює новий потік файлу для читання json-файлу | |
| var read = new FileStream(filePath, FileMode.Open, FileAccess.Read); | |
| // завантажує об'єкт, збережений вище, за допомогою deserialize | |
| var copy = JsonSerializer.Deserialize<SuperHero>(read, options); | |
| read.Close(); | |
| // зауважте: вік не серіалізується через jsonignore, тому буде 0 після десеріалізації | |
| System.Console.WriteLine("Ім'я:\t\t" + copy?.Name); | |
| System.Console.WriteLine("Вік:\t\t" + copy?.Age); | |
| System.Console.WriteLine("Чи злий:\t" + copy?.IsEvil); | |
| System.Console.WriteLine("Чи унікальний:\t" + copy?.Superpower.IsUnique); | |
| System.Console.WriteLine("\nСписок навичок:"); | |
| foreach (var skill in copy?.Superpower.Abilities ?? new string[0]) | |
| { | |
| System.Console.WriteLine("\t" + skill); | |
| } | |
| // очищає тимчасовий файл після використання | |
| // File.Delete(filePath); // перевірити наявність файла в папці проєкта | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment