-
-
Notifications
You must be signed in to change notification settings - Fork 390
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Newtonsoft serializer to test project
add tests later, maybe
- Loading branch information
Showing
3 changed files
with
47 additions
and
1 deletion.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
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); | ||
} | ||
} | ||
} |
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