root / trunk / hammock / src / net35 / Hammock / Serialization / HammockDataContractJsonSerializer.cs @ 0eea575a
History | View | Annotate | Download (2.5 kB)
1 |
using System; |
---|---|
2 |
using System.Collections.Generic; |
3 |
#if NET40 |
4 |
using System.Dynamic; |
5 |
#endif |
6 |
using System.IO; |
7 |
using System.Runtime.Serialization.Json; |
8 |
|
9 |
namespace Hammock.Serialization |
10 |
{ |
11 |
#if !SILVERLIGHT |
12 |
[Serializable] |
13 |
#endif |
14 |
public class HammockDataContractJsonSerializer : Utf8Serializer, ISerializer, IDeserializer |
15 |
{ |
16 |
private readonly Dictionary<RuntimeTypeHandle, DataContractJsonSerializer> _serializers = |
17 |
new Dictionary<RuntimeTypeHandle, DataContractJsonSerializer>(); |
18 |
|
19 |
#region ISerializer Members |
20 |
|
21 |
public virtual string Serialize(object instance, Type type) |
22 |
{ |
23 |
string result; |
24 |
using (var stream = new MemoryStream()) |
25 |
{ |
26 |
var serializer = CacheOrGetSerializerFor(type); |
27 |
serializer.WriteObject(stream, instance); |
28 |
|
29 |
var data = stream.ToArray(); |
30 |
result = ContentEncoding.GetString(data, 0, data.Length); |
31 |
} |
32 |
return result; |
33 |
} |
34 |
|
35 |
public virtual string ContentType |
36 |
{ |
37 |
get { return "application/json"; } |
38 |
} |
39 |
|
40 |
#endregion |
41 |
|
42 |
#region IDeserializer Members |
43 |
|
44 |
public virtual object Deserialize(RestResponseBase response, Type type) |
45 |
{ |
46 |
object instance; |
47 |
using (var stream = new MemoryStream(ContentEncoding.GetBytes(response.Content))) |
48 |
{ |
49 |
var serializer = CacheOrGetSerializerFor(type); |
50 |
instance = serializer.ReadObject(stream); |
51 |
} |
52 |
return instance; |
53 |
} |
54 |
|
55 |
public virtual T Deserialize<T>(RestResponseBase response) |
56 |
{ |
57 |
var type = typeof (T); |
58 |
T instance; |
59 |
using (var stream = new MemoryStream(ContentEncoding.GetBytes(response.Content))) |
60 |
{ |
61 |
var serializer = CacheOrGetSerializerFor(type); |
62 |
instance = (T) serializer.ReadObject(stream); |
63 |
} |
64 |
return instance; |
65 |
} |
66 |
|
67 |
#if NET40 |
68 |
public dynamic DeserializeDynamic(RestResponseBase response) |
69 |
{ |
70 |
throw new NotSupportedException(); |
71 |
} |
72 |
#endif |
73 |
|
74 |
#endregion |
75 |
|
76 |
private DataContractJsonSerializer CacheOrGetSerializerFor(Type type) |
77 |
{ |
78 |
var handle = type.TypeHandle; |
79 |
if (_serializers.ContainsKey(handle)) |
80 |
{ |
81 |
return _serializers[handle]; |
82 |
} |
83 |
|
84 |
var serializer = new DataContractJsonSerializer(type); |
85 |
_serializers.Add(handle, serializer); |
86 |
|
87 |
return serializer; |
88 |
} |
89 |
} |
90 |
} |