75 lines
2.3 KiB
C#
75 lines
2.3 KiB
C#
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("Тест завершен успешно!");
|
||
|