Сценарии

Редактировал(а) Alexandr Fokin 2025/02/17 00:08

JsonDocument Dispose

Обращаю внимание, что JsonDocument реализует интерфейс IDisposable (скорее всего для переиспользования памяти).
Не всегда удобно (особенно, если это часть Entity/Dto), но если нужно снизить нагрузку на GC (финализацию), то нужно всегда вызывать Dispose.

Memory management when using JsonDocument
https://github.com/npgsql/efcore.pg/issues/1746

UPD1:
JsonDocument is IDisposable
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/use-dom#jsondocument-is-idisposable

В документации сказано, что допустимо использовать JsonElement, выполнив следующую код:
public JsonElement GetJson(string jsonString)
{
   using (JsonDocument doc = JsonDocument.Parse(jsonString))
    {
       return doc.RootElement.Clone();
    }
}

Базовые опции

How to customize character encoding with System.Text.Json
https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-character-encoding

new JsonSerializerOptions()
{
 //Игнорирование null элементы
 IgnoreNullValues = true,
 // Форматирование читаемое/компкатный
 WriteIndented = true,

 // Кодировка символов
 //Encoder = JavaScriptEncoder.Create(UnicodeRanges.BasicLatin, UnicodeRanges.Cyrillic),
 Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,

 // Регистронезависимость
 // How to enable case-insensitive property name matching with System.Text.Json
 // https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/character-casing
 PropertyNameCaseInsensitive = true,

 // Enum как строка
 Converters = {                
   new System.Text.Json.Serialization.JsonStringEnumConverter()            
  }
};
Создание или изменение json объекта
Распознать строковые значения как число.[JsonNumberHandling(JsonNumberHandling.AllowReadingFromString)]
// или
new JsonSerializerOptions()
{
    NumberHandling = JsonNumberHandling.AllowReadingFromString
}
JsonConverter.
Реализация собственной (кастомной) логики сериализации типов

How to write custom converters for JSON serialization (marshalling) in .NET
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/converters-how-to?pivots=dotnet-6-0

System.Text.Json deserialization fails with JsonException "read to much or not enough"
https://stackoverflow.com/questions/62147178/system-text-json-deserialization-fails-with-jsonexception-read-to-much-or-not-e

Обход свойствEnumerateObject()
Теги: