Создаем портфолио за 1 месяц
К концу месяца: 4 классных проекта в вашем портфолио! Стоимость: 100$. Подробности...
1284 of 1492 menu
◀ ▶

WriteIndented

WriteIndented = true вставляет символ \\n независимо от ОС. Проверяют через Contains, а не фиксируют весь документ целиком. Часть JsonSerializerOptions.

Синтаксис

options.WriteIndented = true;

Пример

Давайте сериализовать с отступами:

using System; using System.Text.Json; class Item { public string Name { get; set; } } class Program { static void Main() { var options = new JsonSerializerOptions { WriteIndented = true }; Item item = new Item { Name = "abcde" }; string res = JsonSerializer.Serialize(item, options); Console.WriteLine(res.Contains('\n')); } }

Результат выполнения кода:

True

Пример

Давайте сериализовать без отступов:

using System; using System.Text.Json; class Item { public string Name { get; set; } } class Program { static void Main() { Item item = new Item { Name = "abcde" }; string res = JsonSerializer.Serialize(item); Console.WriteLine(res.Contains('\n')); } }

Результат выполнения кода:

False

Пример

Давайте сравнить длину строки:

using System; using System.Text.Json; class Item { public string Name { get; set; } public int Count { get; set; } } class Program { static void Main() { var options = new JsonSerializerOptions { WriteIndented = true }; Item item = new Item { Name = "abcde", Count = 12345 }; string plain = JsonSerializer.Serialize(item); string indented = JsonSerializer.Serialize(item, options); bool res = indented.Length > plain.Length; Console.WriteLine(res); } }

Результат выполнения кода:

True

Смотрите также

← →
↑
Мы используем cookie для работы сайта, аналитики и персонализации. Обработка данных происходит согласно Политике конфиденциальности.
принять все настроить отклонить