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
Смотрите также
-
Serialize,
запись JSON -
JsonSerializerOptions,
объект настроек -
JavaScriptEncoder,
экранирование -
PropertyNamingPolicy,
имена свойств