前段时间用到vs2002开发,很多新技术都用不进去,json没法用,为了实现无刷新保存多条数据(多个对象),前台可以存对象但是无法传到后台,所以采用ajax在后台调用给类SerializeObjectClass.GetString(object _obj)方法把对象转换成字符串后,再返回给前台保存,方便再一次添加数据。点击保存时将该字符串传给后台,后台再次调用该类的SerializeObjectClass.GetObject(string _formatString)方法还原成对象进行保存。
该类代码如下。(作用可以将对象转换成字符串,并可以把字符串还原成对象)
using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
//##############################
//Author: LSQ
//Date :20111007
//##############################
namespace test
{
/// <summary>
/// Summary description for SerializeObjectClass.
/// </summary>
public class SerializeObjectClass
{
public SerializeObjectClass()
{
//
// TODO: Add constructor logic here
//
}
#region Private Method
private static bool CheckBytesIsEqual(byte[] bt1, byte[] bt2)
{
bool b = true;
for (int i = 0; i < bt1.Length; i++)
{
if (bt1[i] != bt2[i])
b = false;
}
return b;
}
private static byte[] Serialize(object obj)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
ms.Seek(0, SeekOrigin.Begin);
BinaryReader br = new BinaryReader(ms);
byte[] bt = br.ReadBytes((int)ms.Length);
return bt;
}
private static object Deserialize(byte[] _bt)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream(_bt);
object obj = bf.Deserialize(ms);
return obj;
}
private static string GetStringFromBytes(byte[] _bt)
{
StringBuilder sb = new StringBuilder();
foreach (byte b in _bt)
{
if (b.ToString().Length == 1)
sb.Append("00" + b.ToString());
else if (b.ToString().Length == 2)
sb.Append("0" + b.ToString());
else if (b.ToString().Length == 3)
sb.Append(b.ToString());
}
return sb.ToString();
}
private static byte[] GetBytesFromString(string _str)
{
byte[] _bt = new byte[_str.Length / 3];
string _tmp = "";
int _count = 0;
int _index = 0;
while (_index < _str.Length / 3)
{
_tmp = _str.Substring(_count, 3);
_bt[_index] = (byte)(int.Parse(_tmp));
_count += 3;
_index += 1;
}
return _bt;
}
#endregion
#region Public Method
public static string GetString(object _obj)
{
return SerializeObjectClass.GetStringFromBytes(SerializeObjectClass.Serialize(_obj));
}
public static object GetObject(string _formatString)
{
return SerializeObjectClass.Deserialize(SerializeObjectClass.GetBytesFromString(_formatString));
}
#endregion
}
//Below class is a test
[Serializable]
public class TT
{
public string aa;
public string bb;
public string cc;
public string get()
{
return "123";
}
}
}