-
-
Notifications
You must be signed in to change notification settings - Fork 244
/
Copy pathISerializer.cs
85 lines (68 loc) · 2.37 KB
/
ISerializer.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System;
using System.IO;
using System.Text;
namespace Foundatio.Serializer;
public interface ISerializer
{
object Deserialize(Stream data, Type objectType);
void Serialize(object value, Stream output);
}
public interface ITextSerializer : ISerializer { }
public static class DefaultSerializer
{
public static ISerializer Instance { get; set; } = new SystemTextJsonSerializer();
}
public static class SerializerExtensions
{
public static T Deserialize<T>(this ISerializer serializer, Stream data)
{
return (T)serializer.Deserialize(data, typeof(T));
}
public static T Deserialize<T>(this ISerializer serializer, byte[] data)
{
return (T)serializer.Deserialize(new MemoryStream(data), typeof(T));
}
public static object Deserialize(this ISerializer serializer, byte[] data, Type objectType)
{
return serializer.Deserialize(new MemoryStream(data), objectType);
}
public static T Deserialize<T>(this ISerializer serializer, string data)
{
byte[] bytes;
if (data == null)
bytes = Array.Empty<byte>();
else if (serializer is ITextSerializer)
bytes = Encoding.UTF8.GetBytes(data);
else
bytes = Convert.FromBase64String(data);
return (T)serializer.Deserialize(new MemoryStream(bytes), typeof(T));
}
public static object Deserialize(this ISerializer serializer, string data, Type objectType)
{
byte[] bytes;
if (data == null)
bytes = Array.Empty<byte>();
else if (serializer is ITextSerializer)
bytes = Encoding.UTF8.GetBytes(data);
else
bytes = Convert.FromBase64String(data);
return serializer.Deserialize(new MemoryStream(bytes), objectType);
}
public static string SerializeToString<T>(this ISerializer serializer, T value)
{
if (value == null)
return null;
var bytes = serializer.SerializeToBytes(value);
if (serializer is ITextSerializer)
return Encoding.UTF8.GetString(bytes);
return Convert.ToBase64String(bytes);
}
public static byte[] SerializeToBytes<T>(this ISerializer serializer, T value)
{
if (value == null)
return null;
var stream = new MemoryStream();
serializer.Serialize(value, stream);
return stream.ToArray();
}
}