Created
June 4, 2022 21:36
-
-
Save tmenier/158ede5f33703036a0c26080adf2b8b9 to your computer and use it in GitHub Desktop.
A Newtonsoft-based JSON serializer for Flurl.Http 4+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using Newtonsoft.Json; | |
namespace Flurl.Http.Configuration | |
{ | |
/// <summary> | |
/// ISerializer implementation based on Newtonsoft.Json. | |
/// Default serializer used in calls to GetJsonAsync, PostJsonAsync, etc. | |
/// </summary> | |
public class NewtonsoftJsonSerializer : ISerializer | |
{ | |
private readonly JsonSerializerSettings _settings; | |
/// <summary> | |
/// Initializes a new instance of the <see cref="NewtonsoftJsonSerializer"/> class. | |
/// </summary> | |
/// <param name="settings">Settings to control (de)serialization behavior.</param> | |
public NewtonsoftJsonSerializer(JsonSerializerSettings settings = null) { | |
_settings = settings; | |
} | |
/// <summary> | |
/// Serializes the specified object to a JSON string. | |
/// </summary> | |
/// <param name="obj">The object to serialize.</param> | |
public string Serialize(object obj) => JsonConvert.SerializeObject(obj, _settings); | |
/// <summary> | |
/// Deserializes the specified JSON string to an object of type T. | |
/// </summary> | |
/// <param name="s">The JSON string to deserialize.</param> | |
public T Deserialize<T>(string s) => JsonConvert.DeserializeObject<T>(s, _settings); | |
/// <summary> | |
/// Deserializes the specified stream to an object of type T. | |
/// </summary> | |
/// <param name="stream">The stream to deserialize.</param> | |
public T Deserialize<T>(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<T>(jr); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Flurl 4.0 removes the dependency on Newtonsoft.Json in favor of System.Text.Json, but I expect many will continue to prefer the former. This serializer can simply be copied into your code base and registered globally by adding this to your app startup code: