Files
YandexMusic/YandexMusic.API/Converters/StringToIntConverter.cs
FrigaT ea9f392896
All checks were successful
Release / pack-and-publish (release) Successful in 9m39s
Добавлен конвертер string->int
2026-04-14 21:25:59 +03:00

42 lines
1.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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);
}
}