JsonRequired
Без ключа свойства
JsonSerializer.Deserialize
бросает
JsonException.
null в JSON - ключ
присутствует, это не то же самое,
что отсутствие. Скрыть поле -
JsonIgnore,
имя ключа -
JsonPropertyName.
Синтаксис
using System.Text.Json.Serialization;
[JsonRequired]
public string Name { get; set; }
Пример
Давайте прочитать пустой объект:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
class Need
{
[JsonRequired]
public string Name { get; set; }
}
class Program
{
static void Main()
{
try
{
JsonSerializer.Deserialize<Need>("{}");
}
catch (JsonException)
{
Console.WriteLine("fail");
}
}
}
Результат выполнения кода:
"fail"
Пример
Давайте прочитать JSON с ключом
Name:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
class Need
{
[JsonRequired]
public string Name { get; set; }
}
class Program
{
static void Main()
{
var need = JsonSerializer.Deserialize<Need>(
"{\"Name\":\"abcde\"}");
string res = need.Name;
Console.WriteLine(res);
}
}
Результат выполнения кода:
"abcde"
Пример
Давайте прочитать null для
обязательного свойства:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
class Need
{
[JsonRequired]
public string Name { get; set; }
}
class Program
{
static void Main()
{
var need = JsonSerializer.Deserialize<Need>(
"{\"Name\":null}");
bool res = need.Name == null;
Console.WriteLine(res);
}
}
Результат выполнения кода:
True
Смотрите также
-
JsonIgnore,
не писать поле -
JsonPropertyName,
имя в JSON -
JsonInclude,
включить непубличное -
JsonExtensionData,
лишние поля