forked from NancyFx/Nancy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDefaultObjectSerializer.cs
More file actions
71 lines (62 loc) · 1.97 KB
/
Copy pathDefaultObjectSerializer.cs
File metadata and controls
71 lines (62 loc) · 1.97 KB
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
namespace Nancy
{
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
public class DefaultObjectSerializer : IObjectSerializer
{
/// <summary>
/// Serialize an object
/// </summary>
/// <param name="sourceObject">Source object</param>
/// <returns>Serialised object string</returns>
public string Serialize(object sourceObject)
{
if (sourceObject == null)
{
return String.Empty;
}
var formatter = new BinaryFormatter();
using (var outputStream = new MemoryStream())
{
formatter.Serialize(outputStream, sourceObject);
var outputBytes = outputStream.GetBuffer();
return Convert.ToBase64String(outputBytes, 0, (int)outputStream.Length);
}
}
/// <summary>
/// Deserialize an object string
/// </summary>
/// <param name="sourceString">Source object string</param>
/// <returns>Deserialized object</returns>
public object Deserialize(string sourceString)
{
if (string.IsNullOrEmpty(sourceString))
{
return null;
}
try
{
var inputBytes = Convert.FromBase64String(sourceString);
var formatter = new BinaryFormatter();
using (var inputStream = new MemoryStream(inputBytes, false))
{
return formatter.Deserialize(inputStream);
}
}
catch (FormatException)
{
return null;
}
catch (SerializationException)
{
return null;
}
catch (IOException)
{
return null;
}
}
}
}