Skip to content

Commit

Permalink
add newtonsoft async deserialization support
Browse files Browse the repository at this point in the history
  • Loading branch information
aspriddell committed Jan 15, 2023
1 parent 0be6b23 commit a65ddc4
Showing 1 changed file with 26 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -38,20 +39,16 @@ public override HttpContent Serialize(object input)

public override T Deserialize<T>(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<T>(reader);
}

using var reader = new JsonTextReader(sr)
{
ArrayPool = JsonArrayPool.Instance
};
public async ValueTask<T> DeserializeAsync<T>(Stream input) where T : class
{
var reader = GetReader(input);
var token = await JToken.LoadAsync(reader).ConfigureAwait(false);

return Serializer.Deserialize<T>(reader);
return token.ToObject<T>();
}

/// <summary>
Expand All @@ -63,5 +60,21 @@ public static void RegisterDefaults()
SerializerResolver.Register<JToken, ApiJsonSerializer>();
SerializerResolver.Register<JObject, ApiJsonSerializer>();
}

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
};
}
}
}

0 comments on commit a65ddc4

Please sign in to comment.