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

Копия текущей версии из github
author cin
date Thu, 27 Mar 2014 21:46:09 +0400
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Source/Mapping/MemberMappers/JSONSerialisationMapper.cs	Thu Mar 27 21:46:09 2014 +0400
@@ -0,0 +1,49 @@
+using System;
+using System.IO;
+using System.Runtime.Serialization.Json;
+using System.Text;
+
+namespace BLToolkit.Mapping.MemberMappers
+{
+	public class JSONSerialisationMapper : MemberMapper
+	{
+		public override void SetValue(object o, object value)
+		{
+			if (value != null) this.MemberAccessor.SetValue(o, Deserialize(value.ToString()));
+		}
+
+        public override object GetValue(object o)
+        {
+            return this.serialize(this.MemberAccessor.GetValue(o));
+        }
+
+        private string serialize(object obj)
+        {
+            if (obj == null) return null;
+
+			DataContractJsonSerializer ser = new DataContractJsonSerializer(this.Type);
+			MemoryStream ms = new MemoryStream();
+			ser.WriteObject(ms, obj);
+			string jsonString = Encoding.UTF8.GetString(ms.ToArray());
+			ms.Close();
+			return jsonString;   
+		}
+
+		object Deserialize(string txt)
+		{
+			object retVal = null;
+			if (string.IsNullOrEmpty(txt)) return null;
+
+			try
+			{
+				DataContractJsonSerializer ser = new DataContractJsonSerializer(this.Type);
+				MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(txt));
+				retVal = ser.ReadObject(ms);                
+			}
+			catch (Exception)
+			{
+			}
+			return retVal;
+		}
+	}
+}