Skip to content

Instantly share code, notes, and snippets.

@tmenier
Created June 4, 2022 21:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmenier/158ede5f33703036a0c26080adf2b8b9 to your computer and use it in GitHub Desktop.
Save tmenier/158ede5f33703036a0c26080adf2b8b9 to your computer and use it in GitHub Desktop.
A Newtonsoft-based JSON serializer for Flurl.Http 4+
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);
}
}
}
@tmenier
Copy link
Author

tmenier commented Jun 4, 2022

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:

FlurlHttp.GlobalSettings.JsonSerializer = new NewtonsoftJsonSerializer();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment