From 869e9c6acd1437a9bfa68ba96bcee0593cc92b25 Mon Sep 17 00:00:00 2001 From: Todd Date: Sun, 5 Jun 2022 11:58:39 -0500 Subject: [PATCH] Add Newtonsoft serializer to test project add tests later, maybe --- Test/Flurl.Test/Flurl.Test.csproj | 2 + .../Http/NewtonsoftJsonSerializer .cs | 45 +++++++++++++++++++ .../Configuration/DefaultJsonSerializer.cs | 1 - 3 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 Test/Flurl.Test/Http/NewtonsoftJsonSerializer .cs diff --git a/Test/Flurl.Test/Flurl.Test.csproj b/Test/Flurl.Test/Flurl.Test.csproj index 7333c56b..1bb1ec68 100644 --- a/Test/Flurl.Test/Flurl.Test.csproj +++ b/Test/Flurl.Test/Flurl.Test.csproj @@ -1,6 +1,7 @@ net6.0;net48;net461 + 8.0 @@ -9,6 +10,7 @@ all + diff --git a/Test/Flurl.Test/Http/NewtonsoftJsonSerializer .cs b/Test/Flurl.Test/Http/NewtonsoftJsonSerializer .cs new file mode 100644 index 00000000..d998ae4a --- /dev/null +++ b/Test/Flurl.Test/Http/NewtonsoftJsonSerializer .cs @@ -0,0 +1,45 @@ +using System.IO; +using Newtonsoft.Json; + +namespace Flurl.Http.Configuration +{ + /// + /// ISerializer implementation based on Newtonsoft.Json. + /// Default serializer used in calls to GetJsonAsync, PostJsonAsync, etc. + /// + public class NewtonsoftJsonSerializer : ISerializer + { + private readonly JsonSerializerSettings _settings; + + /// + /// Initializes a new instance of the class. + /// + /// Settings to control (de)serialization behavior. + public NewtonsoftJsonSerializer(JsonSerializerSettings settings = null) { + _settings = settings; + } + + /// + /// Serializes the specified object to a JSON string. + /// + /// The object to serialize. + public string Serialize(object obj) => JsonConvert.SerializeObject(obj, _settings); + + /// + /// Deserializes the specified JSON string to an object of type T. + /// + /// The JSON string to deserialize. + public T Deserialize(string s) => JsonConvert.DeserializeObject(s, _settings); + + /// + /// Deserializes the specified stream to an object of type T. + /// + /// The stream to deserialize. + public T Deserialize(Stream stream) { + // https://www.newtonsoft.com/json/help/html/Performance.htm#MemoryUsage + using var sr = new StreamReader(stream); + using var jr = new JsonTextReader(sr); + return JsonSerializer.CreateDefault(_settings).Deserialize(jr); + } + } +} \ No newline at end of file diff --git a/src/Flurl.Http/Configuration/DefaultJsonSerializer.cs b/src/Flurl.Http/Configuration/DefaultJsonSerializer.cs index 2487560d..e6a3c0d6 100644 --- a/src/Flurl.Http/Configuration/DefaultJsonSerializer.cs +++ b/src/Flurl.Http/Configuration/DefaultJsonSerializer.cs @@ -1,5 +1,4 @@ using System.IO; -using System.Security.Cryptography; using System.Text.Json; namespace Flurl.Http.Configuration