|
2 | 2 | using System.Text; |
3 | 3 | using Newtonsoft.Json; |
4 | 4 |
|
5 | | -namespace CacheTower.Serializers.NewtonsoftJson |
| 5 | +namespace CacheTower.Serializers.NewtonsoftJson; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// Allows serializing to and from JSON via Newtonsoft.Json |
| 9 | +/// </summary> |
| 10 | +public class NewtonsoftJsonCacheSerializer : ICacheSerializer |
6 | 11 | { |
| 12 | + private readonly JsonSerializer serializer; |
| 13 | + |
7 | 14 | /// <summary> |
8 | | - /// Allows serializing to and from JSON via Newtonsoft.Json |
| 15 | + /// An existing instance of <see cref="NewtonsoftJsonCacheSerializer"/>. |
9 | 16 | /// </summary> |
10 | | - public class NewtonsoftJsonCacheSerializer : ICacheSerializer |
| 17 | + public static NewtonsoftJsonCacheSerializer Instance { get; } = new(); |
| 18 | + |
| 19 | + private NewtonsoftJsonCacheSerializer() |
11 | 20 | { |
12 | | - /// <summary> |
13 | | - /// An existing instance of <see cref="NewtonsoftJsonCacheSerializer"/>. |
14 | | - /// </summary> |
15 | | - public static NewtonsoftJsonCacheSerializer Instance { get; } = new(); |
| 21 | + serializer = new JsonSerializer(); |
| 22 | + } |
16 | 23 |
|
17 | | - private JsonSerializer Serializer { get; } = new JsonSerializer(); |
| 24 | + /// <summary> |
| 25 | + /// Creates a new instance of <see cref="NewtonsoftJsonCacheSerializer"/> with the specified <paramref name="settings"/>. |
| 26 | + /// </summary> |
| 27 | + public NewtonsoftJsonCacheSerializer(JsonSerializerSettings settings) |
| 28 | + { |
| 29 | + serializer = JsonSerializer.Create(settings); |
| 30 | + } |
18 | 31 |
|
19 | | - /// <inheritdoc /> |
20 | | - public void Serialize<T>(Stream stream, T? value) |
21 | | - { |
22 | | - using var streamWriter = new StreamWriter(stream, Encoding.UTF8, 1024, true); |
23 | | - using var jsonWriter = new JsonTextWriter(streamWriter); |
24 | | - Serializer.Serialize(jsonWriter, value); |
25 | | - } |
| 32 | + /// <inheritdoc /> |
| 33 | + public void Serialize<T>(Stream stream, T? value) |
| 34 | + { |
| 35 | + using var streamWriter = new StreamWriter(stream, Encoding.UTF8, 1024, true); |
| 36 | + using var jsonWriter = new JsonTextWriter(streamWriter); |
| 37 | + serializer.Serialize(jsonWriter, value); |
| 38 | + } |
26 | 39 |
|
27 | | - /// <inheritdoc /> |
28 | | - public T? Deserialize<T>(Stream stream) |
29 | | - { |
30 | | - using var streamReader = new StreamReader(stream, Encoding.UTF8, false, 1024); |
31 | | - using var jsonReader = new JsonTextReader(streamReader); |
32 | | - return Serializer.Deserialize<T>(jsonReader); |
33 | | - } |
| 40 | + /// <inheritdoc /> |
| 41 | + public T? Deserialize<T>(Stream stream) |
| 42 | + { |
| 43 | + using var streamReader = new StreamReader(stream, Encoding.UTF8, false, 1024); |
| 44 | + using var jsonReader = new JsonTextReader(streamReader); |
| 45 | + return serializer.Deserialize<T>(jsonReader); |
34 | 46 | } |
35 | 47 | } |
0 commit comments