ReadCommentHandling
По умолчанию Disallow: комментарий
"/*x*/" даёт JsonException.
JsonCommentHandling.Skip пропускает
комментарий, и Name читается как
"abcde". Задаётся в
JsonSerializerOptions.
Синтаксис
options.ReadCommentHandling = JsonCommentHandling.Skip;
Пример
Давайте пропустить комментарий:
using System;
using System.Text.Json;
class Item
{
public string Name { get; set; }
}
class Program
{
static void Main()
{
var options = new JsonSerializerOptions
{
ReadCommentHandling = JsonCommentHandling.Skip
};
Item item = JsonSerializer.Deserialize<Item>(
"/*x*/{\"Name\":\"abcde\"}", options);
Console.WriteLine(item.Name);
}
}
Результат выполнения кода:
"abcde"
Пример
Давайте разобрать с Disallow:
using System;
using System.Text.Json;
class Item
{
public string Name { get; set; }
}
class Program
{
static void Main()
{
try
{
JsonSerializer.Deserialize<Item>(
"/*x*/{\"Name\":\"abcde\"}");
}
catch (JsonException)
{
Console.WriteLine("fail");
}
}
}
Результат выполнения кода:
"fail"
Пример
Давайте разобрать JSON без комментария:
using System;
using System.Text.Json;
class Item
{
public string Name { get; set; }
}
class Program
{
static void Main()
{
var options = new JsonSerializerOptions
{
ReadCommentHandling = JsonCommentHandling.Skip
};
Item item = JsonSerializer.Deserialize<Item>(
"{\"Name\":\"abcde\"}", options);
Console.WriteLine(item.Name);
}
}
Результат выполнения кода:
"abcde"
Смотрите также
-
AllowTrailingCommas,
хвостовая запятая -
Deserialize,
разбор JSON -
JsonSerializerOptions,
объект настроек -
NumberHandling,
числа в строках