comparison Source/Mapping/MemberMappers/JSONSerialisationMapper.cs @ 0:f990fcb411a9

Копия текущей версии из github
author cin
date Thu, 27 Mar 2014 21:46:09 +0400
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:f990fcb411a9
1 using System;
2 using System.IO;
3 using System.Runtime.Serialization.Json;
4 using System.Text;
5
6 namespace BLToolkit.Mapping.MemberMappers
7 {
8 public class JSONSerialisationMapper : MemberMapper
9 {
10 public override void SetValue(object o, object value)
11 {
12 if (value != null) this.MemberAccessor.SetValue(o, Deserialize(value.ToString()));
13 }
14
15 public override object GetValue(object o)
16 {
17 return this.serialize(this.MemberAccessor.GetValue(o));
18 }
19
20 private string serialize(object obj)
21 {
22 if (obj == null) return null;
23
24 DataContractJsonSerializer ser = new DataContractJsonSerializer(this.Type);
25 MemoryStream ms = new MemoryStream();
26 ser.WriteObject(ms, obj);
27 string jsonString = Encoding.UTF8.GetString(ms.ToArray());
28 ms.Close();
29 return jsonString;
30 }
31
32 object Deserialize(string txt)
33 {
34 object retVal = null;
35 if (string.IsNullOrEmpty(txt)) return null;
36
37 try
38 {
39 DataContractJsonSerializer ser = new DataContractJsonSerializer(this.Type);
40 MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(txt));
41 retVal = ser.ReadObject(ms);
42 }
43 catch (Exception)
44 {
45 }
46 return retVal;
47 }
48 }
49 }