corp-app/test-deserialization.csx

75 lines
2.3 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Text.Json;
using System.Text.Json.Serialization;
// Тестовая модель
public class TestDepartment
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
[JsonPropertyName("employees_count")]
public int EmployeesCount { get; set; }
[JsonIgnore]
public string DisplayDescription =>
string.IsNullOrWhiteSpace(Description)
? "Описание отсутствует"
: Description;
}
// Тестовые данные - то, что приходит с API
string json = @"{
""id"": 1,
""name"": ""IT"",
""description"": ""Отдел информационных технологий"",
""employees_count"": 7
}";
Console.WriteLine("JSON от API:");
Console.WriteLine(json);
Console.WriteLine();
// Десериализация
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
var dept = JsonSerializer.Deserialize<TestDepartment>(json, options);
Console.WriteLine("Результат десериализации:");
Console.WriteLine($"ID: {dept.Id}");
Console.WriteLine($"Name: {dept.Name}");
Console.WriteLine($"Description: '{dept.Description}'");
Console.WriteLine($"Description Length: {dept.Description.Length}");
Console.WriteLine($"EmployeesCount: {dept.EmployeesCount}");
Console.WriteLine($"DisplayDescription: '{dept.DisplayDescription}'");
Console.WriteLine();
// Тест с пустым описанием
string json2 = @"{
""id"": 2,
""name"": ""Маркетинг"",
""description"": """",
""employees_count"": 6
}";
Console.WriteLine("JSON с пустым описанием:");
Console.WriteLine(json2);
Console.WriteLine();
var dept2 = JsonSerializer.Deserialize<TestDepartment>(json2, options);
Console.WriteLine("Результат десериализации:");
Console.WriteLine($"ID: {dept2.Id}");
Console.WriteLine($"Name: {dept2.Name}");
Console.WriteLine($"Description: '{dept2.Description}'");
Console.WriteLine($"Description Length: {dept2.Description.Length}");
Console.WriteLine($"EmployeesCount: {dept2.EmployeesCount}");
Console.WriteLine($"DisplayDescription: '{dept2.DisplayDescription}'");
Console.WriteLine();
Console.WriteLine("Тест завершен успешно!");