Добавлен конвертер string->int
All checks were successful
Release / pack-and-publish (release) Successful in 9m39s
All checks were successful
Release / pack-and-publish (release) Successful in 9m39s
This commit is contained in:
42
YandexMusic.API/Converters/StringToIntConverter.cs
Normal file
42
YandexMusic.API/Converters/StringToIntConverter.cs
Normal file
@@ -0,0 +1,42 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace YandexMusic.API.Converters;
|
||||
|
||||
public class StringToIntConverter : JsonConverter<int>
|
||||
{
|
||||
public override int Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
// Если текущий токен — строка
|
||||
if (reader.TokenType == JsonTokenType.String)
|
||||
{
|
||||
string? stringValue = reader.GetString();
|
||||
if (string.IsNullOrEmpty(stringValue))
|
||||
{
|
||||
throw new JsonException("Строка не может быть пустой или null для преобразования в int.");
|
||||
}
|
||||
|
||||
// Пробуем распарсить с учётом возможных пробелов и инвариантной культуры
|
||||
if (int.TryParse(stringValue.Trim(), out int result))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
throw new JsonException($"Невозможно преобразовать строку \"{stringValue}\" в int.");
|
||||
}
|
||||
|
||||
// Если токен — число (стандартное поведение)
|
||||
if (reader.TokenType == JsonTokenType.Number)
|
||||
{
|
||||
return reader.GetInt32();
|
||||
}
|
||||
|
||||
throw new JsonException($"Ожидалась строка или число, получен {reader.TokenType}.");
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, int value, JsonSerializerOptions options)
|
||||
{
|
||||
// Записываем число как обычное JSON-число
|
||||
writer.WriteNumberValue(value);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user