forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataContractSerializer.cs
More file actions
101 lines (88 loc) · 3.25 KB
/
DataContractSerializer.cs
File metadata and controls
101 lines (88 loc) · 3.25 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using ServiceStack.DesignPatterns.Serialization;
#if !SILVERLIGHT && !MONOTOUCH && !XBOX
using System.IO.Compression;
#endif
namespace ServiceStack.ServiceModel.Serialization
{
public class DataContractSerializer : IStringSerializer
{
private static readonly Encoding Encoding = Encoding.UTF8;// new UTF8Encoding(true);
public static DataContractSerializer Instance = new DataContractSerializer();
public string Parse<XmlDto>(XmlDto from, bool indentXml)
{
try
{
using (var ms = new MemoryStream())
{
var serializer = new System.Runtime.Serialization.DataContractSerializer(from.GetType());
#if !SILVERLIGHT && !MONOTOUCH && !XBOX
using (var xw = new XmlTextWriter(ms, Encoding))
{
if (indentXml)
{
xw.Formatting = Formatting.Indented;
}
serializer.WriteObject(xw, from);
xw.Flush();
#else
serializer.WriteObject(ms, from);
#endif
ms.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(ms))
{
return reader.ReadToEnd();
}
#if !SILVERLIGHT && !MONOTOUCH && !XBOX
}
#endif
}
}
catch (Exception ex)
{
throw new SerializationException(string.Format("Error serializing object of type {0}", from.GetType().FullName), ex);
}
}
public string Parse<XmlDto>(XmlDto from)
{
return Parse(from, false);
}
public void SerializeToStream(object obj, Stream stream)
{
#if !SILVERLIGHT && !MONOTOUCH && !XBOX
using (var xw = new XmlTextWriter(stream, Encoding))
{
var serializer = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());
serializer.WriteObject(xw, obj);
}
#else
var serializer = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());
serializer.WriteObject(stream, obj);
#endif
}
#if !SILVERLIGHT && !MONOTOUCH && !XBOX
public void CompressToStream<XmlDto>(XmlDto from, Stream stream)
{
using (var deflateStream = new DeflateStream(stream, CompressionMode.Compress))
using (var xw = new XmlTextWriter(deflateStream, Encoding))
{
var serializer = new System.Runtime.Serialization.DataContractSerializer(from.GetType());
serializer.WriteObject(xw, from);
xw.Flush();
}
}
public byte[] Compress<XmlDto>(XmlDto from)
{
using (var ms = new MemoryStream())
{
CompressToStream(from, ms);
return ms.ToArray();
}
}
#endif
}
}