Обнновлено до .net10
This commit is contained in:
41
YandexMusic.API/Models/Common/YExecutionContextConverter.cs
Normal file
41
YandexMusic.API/Models/Common/YExecutionContextConverter.cs
Normal file
@@ -0,0 +1,41 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using YandexMusic.API.Common;
|
||||
|
||||
namespace YandexMusic.API.Models.Common;
|
||||
|
||||
/// <summary>Конвертер для внедрения контекста выполнения (API и хранилище) в модели.</summary>
|
||||
public class YExecutionContextConverter : JsonConverter<YBaseModel>
|
||||
{
|
||||
private readonly YandexMusicApi _api;
|
||||
private readonly AuthStorage _storage;
|
||||
|
||||
public YExecutionContextConverter(YandexMusicApi api, AuthStorage storage)
|
||||
{
|
||||
_api = api;
|
||||
_storage = storage;
|
||||
}
|
||||
|
||||
public override YBaseModel? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
{
|
||||
// Десериализуем объект без контекста
|
||||
var obj = (YBaseModel?)JsonSerializer.Deserialize(ref reader, typeToConvert, options);
|
||||
if (obj != null)
|
||||
{
|
||||
obj.Context = new YExecutionContext
|
||||
{
|
||||
API = _api,
|
||||
Storage = _storage
|
||||
};
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, YBaseModel value, JsonSerializerOptions options)
|
||||
{
|
||||
// При сериализации игнорируем контекст
|
||||
var cloneOptions = new JsonSerializerOptions(options);
|
||||
cloneOptions.Converters.Remove(this);
|
||||
JsonSerializer.Serialize(writer, value, cloneOptions);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user