-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNewtonsoftSerializer.cs
73 lines (65 loc) · 2.46 KB
/
NewtonsoftSerializer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.Text;
using NetPro.RedisManager;
using Newtonsoft.Json;
namespace SNetPro.RedisManager
{
/// <summary>
/// JSon.Net implementation of <see cref="ISerializer"/>
/// </summary>
public class NewtonsoftSerializer : ISerializer
{
/// <summary>
/// Encoding to use to convert string to byte[] and the other way around.
/// </summary>
/// <remarks>
/// StackExchange.Redis uses Encoding.UTF8 to convert strings to bytes,
/// hence we do same here.
/// </remarks>
private static readonly Encoding encoding = Encoding.UTF8;
private readonly JsonSerializerSettings settings;
/// <summary>
/// Initializes a new instance of the <see cref="NewtonsoftSerializer"/> class.
/// </summary>
public NewtonsoftSerializer()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="NewtonsoftSerializer"/> class.
/// </summary>
/// <param name="settings">The settings.</param>
public NewtonsoftSerializer(JsonSerializerSettings settings)
{
this.settings = settings ?? new JsonSerializerSettings();
}
/// <inheritdoc/>
public byte[] Serialize(object item)
{
var type = item?.GetType();
var jsonString = JsonConvert.SerializeObject(item, type, settings);
jsonString = jsonString.TrimStart('\"').TrimEnd('\"');
return encoding.GetBytes(jsonString);
}
/// <inheritdoc/>
public T Deserialize<T>(byte[] serializedObject)
{
var jsonString = encoding.GetString(serializedObject);
jsonString = jsonString.TrimStart('\"').TrimEnd('\"');
if (typeof(T) == typeof(string) || typeof(T).IsValueType) { return (T)Convert.ChangeType(jsonString, typeof(T)); }
return JsonConvert.DeserializeObject<T>(jsonString, settings);
}
private object GetDefault(Type type)
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
var valueProperty = type.GetProperty("Value");
type = valueProperty.PropertyType;
}
return type.IsValueType ? Activator.CreateInstance(type) : null;
}
}
}