diff --git a/serializers/DragonFruit.Data.Serializers.Newtonsoft/ApiJsonSerializer.cs b/serializers/DragonFruit.Data.Serializers.Newtonsoft/ApiJsonSerializer.cs index 9f9daef..137c336 100644 --- a/serializers/DragonFruit.Data.Serializers.Newtonsoft/ApiJsonSerializer.cs +++ b/serializers/DragonFruit.Data.Serializers.Newtonsoft/ApiJsonSerializer.cs @@ -3,13 +3,14 @@ using System.IO; using System.Net.Http; +using System.Threading.Tasks; using DragonFruit.Data.Utils; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace DragonFruit.Data.Serializers.Newtonsoft { - public class ApiJsonSerializer : ApiSerializer + public class ApiJsonSerializer : ApiSerializer, IAsyncSerializer { private JsonSerializer _serializer; @@ -38,20 +39,16 @@ public override HttpContent Serialize(object input) public override T Deserialize(Stream input) where T : class { - using var sr = AutoDetectEncoding switch - { - true => new StreamReader(input, true), - - false when Encoding is null => new StreamReader(input), - false => new StreamReader(input, Encoding) - }; + var reader = GetReader(input); + return Serializer.Deserialize(reader); + } - using var reader = new JsonTextReader(sr) - { - ArrayPool = JsonArrayPool.Instance - }; + public async ValueTask DeserializeAsync(Stream input) where T : class + { + var reader = GetReader(input); + var token = await JToken.LoadAsync(reader).ConfigureAwait(false); - return Serializer.Deserialize(reader); + return token.ToObject(); } /// @@ -63,5 +60,21 @@ public static void RegisterDefaults() SerializerResolver.Register(); SerializerResolver.Register(); } + + private JsonTextReader GetReader(Stream input) + { + var sr = AutoDetectEncoding switch + { + true => new StreamReader(input, true), + + false when Encoding is null => new StreamReader(input), + false => new StreamReader(input, Encoding) + }; + + return new JsonTextReader(sr) + { + ArrayPool = JsonArrayPool.Instance + }; + } } }