Silverlight,原来的序列化不好,自己开发一个。
主要处理值类型,但是常常有List<T>,Collection<T>没有处理那位帮忙:
提供源代码:但是没有实现这个,那位帮忙实现序列化反序列化。
/// <summary>
/// 对象序列化:
/// 由于需要提供个可以兼容的序列化工具
/// 开发目的:
/// 1.避免C#的序列化反序列化带来的成员变化的BUG。
/// 2.可以强制序列化只读具备【XMLWriter】的属性。
/// 3.避免WPF序列化子成员构建带来的子对象的依赖属性事件丢失的现象
/// 4.提供多个版本的兼容工具
/// 5.(Stream stream, object o),(TextWriter textWriter, object o);(XmlWriter xmlWriter, object o);
/// 特别注意:
/// 1.暂时不知泛型以及IList以及数组,需要扩展支持!!!!
/// </summary>
public class ObjectSerializer<T> where T : new()
{
private readonly string xmlns_prefix_xsi=@"http://www.w3.org/2001/XMLSchema-instance";//xmlns:xsi
private readonly string xmlns_prefix_xsd=@"http://www.w3.org/2001/XMLSchema";//xmlns:xsd /// <summary>
/// 不知何故,微软的Siverlight的Type的IsSerializable成了保护级别,无法访问。
/// 自己做一个判定是否可以序列化
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
private bool IsSerializable(Type t)
{
switch (Type.GetTypeCode(t))
{
case TypeCode.Object:
return false;
default:
return true;
}
} #region 序列化
public void Serialize(TextWriter textWriter, object o)
{
Serialize(o).Save(textWriter);
} public void Serialize(XmlWriter xmlWriter, object o)
{
Serialize(o).Save(xmlWriter);
} public void Serialize(Stream stream, object o)
{
Serialize(o).Save(stream);
} private XDocument Serialize(object o)
{
XDocument doc=new XDocument(new XComment("Richwork Framework 自定义生成"));
XElement element=new XElement(
o.GetType().Name,
new XAttribute(XNamespace.Xmlns+"xsi",xmlns_prefix_xsi),
new XAttribute(XNamespace.Xmlns+"xsd",xmlns_prefix_xsd)); SerializeProperty(o, element); doc.Add(element);
return doc;
} private void SerializeProperty(object o, XElement root)
{
Type t =o.GetType();
PropertyInfo[] properties =t.GetProperties(); foreach ( PropertyInfo pi in properties )//记录当前对象的成员
{
var Att = pi.GetCustomAttributes(typeof(XmlWriterAttribute), false).FirstOrDefault();//[i].GetCustomAttributes(true);Object[]
if ((pi.CanWrite) ||
(Att !=null))
{
object value=pi.GetValue(o, null);
if (IsSerializable(pi.PropertyType))
{
root.Add(new XElement(pi.Name,value));
}
else
{
XElement element=new XElement(pi.Name);
SerializeProperty(value, element);
root.Add(element);
}
} }
//return root;
} #endregion #region 反序列化
public T Deserialize(Stream stream,object o)
{
XDocument doc=XDocument.Load(stream);
return Deserialize(doc, o);
} public T Deserialize(TextReader textReader, object o)
{
XDocument doc=XDocument.Load(textReader);//未判断缺少根元素的错误,或者提供一个捕获错误的事件。
return Deserialize(doc, o);
} public T Deserialize(XmlReader xmlReader, object o)
{
XDocument doc=XDocument.Load(xmlReader);
return Deserialize(doc, o);
} private T Deserialize(XDocument doc, object o)
{
if ( o == null ) o = new T();//T o=new T();//object p =t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null); XElement root=doc.Elements().FirstOrDefault();
if ( root != null )
o = DeserializeProperty(o, root);
return (T)o;
} private object DeserializeProperty(object o, XElement root)
{
Type t =o.GetType();
PropertyInfo[] properties =t.GetProperties(); foreach ( PropertyInfo pi in properties )
{
if ( pi.CanWrite )
{
if ( IsSerializable(pi.PropertyType))
{
XElement element=root.Elements().Where(p => p.Name.LocalName == pi.Name).FirstOrDefault();
//System.Diagnostics.Debug.WriteLine(element);
if ( element != null )
{
try
{
//根据属性的类型进行强制转换对应的类型,可能引发异常,未处理异常
object value=pi.GetValue(o, null);
pi.SetValue(o, Convert.ChangeType(element.Value, pi.PropertyType, null), null);
}
catch
{
pi.SetValue(o, null, null);//异常的是否,使用NULL,暂时这样处理
}
}
}
else //Class is
{
//XElement element=root.Elements().Where(p=>p.Name.Equals(pi.Name)).FirstOrDefault();
//==============
//XElement element=root.Elements().Where(p=>p.
XElement element=root.Elements().Where(p => p.Name.LocalName==pi.Name).FirstOrDefault(); if ( element != null )
{
object value=pi.GetValue(o, null);
DeserializeProperty(value,element); }
}
}//endif
}
//=============================
return o;
}
#endregion
}
}
主要处理值类型,但是常常有List<T>,Collection<T>没有处理那位帮忙:
提供源代码:但是没有实现这个,那位帮忙实现序列化反序列化。
/// <summary>
/// 对象序列化:
/// 由于需要提供个可以兼容的序列化工具
/// 开发目的:
/// 1.避免C#的序列化反序列化带来的成员变化的BUG。
/// 2.可以强制序列化只读具备【XMLWriter】的属性。
/// 3.避免WPF序列化子成员构建带来的子对象的依赖属性事件丢失的现象
/// 4.提供多个版本的兼容工具
/// 5.(Stream stream, object o),(TextWriter textWriter, object o);(XmlWriter xmlWriter, object o);
/// 特别注意:
/// 1.暂时不知泛型以及IList以及数组,需要扩展支持!!!!
/// </summary>
public class ObjectSerializer<T> where T : new()
{
private readonly string xmlns_prefix_xsi=@"http://www.w3.org/2001/XMLSchema-instance";//xmlns:xsi
private readonly string xmlns_prefix_xsd=@"http://www.w3.org/2001/XMLSchema";//xmlns:xsd /// <summary>
/// 不知何故,微软的Siverlight的Type的IsSerializable成了保护级别,无法访问。
/// 自己做一个判定是否可以序列化
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
private bool IsSerializable(Type t)
{
switch (Type.GetTypeCode(t))
{
case TypeCode.Object:
return false;
default:
return true;
}
} #region 序列化
public void Serialize(TextWriter textWriter, object o)
{
Serialize(o).Save(textWriter);
} public void Serialize(XmlWriter xmlWriter, object o)
{
Serialize(o).Save(xmlWriter);
} public void Serialize(Stream stream, object o)
{
Serialize(o).Save(stream);
} private XDocument Serialize(object o)
{
XDocument doc=new XDocument(new XComment("Richwork Framework 自定义生成"));
XElement element=new XElement(
o.GetType().Name,
new XAttribute(XNamespace.Xmlns+"xsi",xmlns_prefix_xsi),
new XAttribute(XNamespace.Xmlns+"xsd",xmlns_prefix_xsd)); SerializeProperty(o, element); doc.Add(element);
return doc;
} private void SerializeProperty(object o, XElement root)
{
Type t =o.GetType();
PropertyInfo[] properties =t.GetProperties(); foreach ( PropertyInfo pi in properties )//记录当前对象的成员
{
var Att = pi.GetCustomAttributes(typeof(XmlWriterAttribute), false).FirstOrDefault();//[i].GetCustomAttributes(true);Object[]
if ((pi.CanWrite) ||
(Att !=null))
{
object value=pi.GetValue(o, null);
if (IsSerializable(pi.PropertyType))
{
root.Add(new XElement(pi.Name,value));
}
else
{
XElement element=new XElement(pi.Name);
SerializeProperty(value, element);
root.Add(element);
}
} }
//return root;
} #endregion #region 反序列化
public T Deserialize(Stream stream,object o)
{
XDocument doc=XDocument.Load(stream);
return Deserialize(doc, o);
} public T Deserialize(TextReader textReader, object o)
{
XDocument doc=XDocument.Load(textReader);//未判断缺少根元素的错误,或者提供一个捕获错误的事件。
return Deserialize(doc, o);
} public T Deserialize(XmlReader xmlReader, object o)
{
XDocument doc=XDocument.Load(xmlReader);
return Deserialize(doc, o);
} private T Deserialize(XDocument doc, object o)
{
if ( o == null ) o = new T();//T o=new T();//object p =t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null); XElement root=doc.Elements().FirstOrDefault();
if ( root != null )
o = DeserializeProperty(o, root);
return (T)o;
} private object DeserializeProperty(object o, XElement root)
{
Type t =o.GetType();
PropertyInfo[] properties =t.GetProperties(); foreach ( PropertyInfo pi in properties )
{
if ( pi.CanWrite )
{
if ( IsSerializable(pi.PropertyType))
{
XElement element=root.Elements().Where(p => p.Name.LocalName == pi.Name).FirstOrDefault();
//System.Diagnostics.Debug.WriteLine(element);
if ( element != null )
{
try
{
//根据属性的类型进行强制转换对应的类型,可能引发异常,未处理异常
object value=pi.GetValue(o, null);
pi.SetValue(o, Convert.ChangeType(element.Value, pi.PropertyType, null), null);
}
catch
{
pi.SetValue(o, null, null);//异常的是否,使用NULL,暂时这样处理
}
}
}
else //Class is
{
//XElement element=root.Elements().Where(p=>p.Name.Equals(pi.Name)).FirstOrDefault();
//==============
//XElement element=root.Elements().Where(p=>p.
XElement element=root.Elements().Where(p => p.Name.LocalName==pi.Name).FirstOrDefault(); if ( element != null )
{
object value=pi.GetValue(o, null);
DeserializeProperty(value,element); }
}
}//endif
}
//=============================
return o;
}
#endregion
}
}
/// 数据序列化
/// </summary>
/// <typeparam name="T"></typeparam>
public static class DataSerializer<T> where T:new()
{
/// <summary>
/// 对象属性克隆
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public static object CloneObject(object o)
{
Type t =o.GetType();
PropertyInfo[] properties =t.GetProperties();
object p =t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null);
foreach ( PropertyInfo pi in properties )
{
if ( pi.CanWrite )
{
object value=pi.GetValue(o, null);
pi.SetValue(p, value, null);
}
}
return p;
} #region //自定义优化加载XML
public static T LoadXML(string xml)
{
object obj = new T();
if ( xml == null ) return (T)obj;
if ( xml == string.Empty ) return (T)obj; System.IO.StringReader reader=new System.IO.StringReader(xml);
ObjectSerializer<T> ser=new ObjectSerializer<T>();
return (T)ser.Deserialize(reader, obj);
} public static string SaveXML(object obj)
{
if ( obj == null ) return ""; System.IO.StringWriter writer=new System.IO.StringWriter();
ObjectSerializer<T> ser = new ObjectSerializer<T>();
ser.Serialize(writer,obj);
return writer.ToString();
}
#endregion
XmlSerializer, Json都可以考虑,而且非常成熟
相对来说,
还是楼主写得好!第一:
楼主开源!
第二:
楼主的easy读懂! 要改变一点代码也easy!第三:
代码短小!便以copy
第一:
.NET的可以Reflector
第二:
使用序列化和反序列化的client根本不CARE代码是不是EASY!我们更关心用这个东西是否安全,包括速度,质量和robust
第三:
采用XmlSerializer和JSON根本无需COPY再补充一下:
采用标准件遇到问题可以找组织,可以google,csdn,stackoverflow,如果用自定义的,那只能找鬼
-------------------- /// <summary>
/// 序列化成字符串
/// </summary>
/// <param name="obj"></param>
/// <returns>序列化后的字符串</returns>
public static string Serialiaze(object obj)
{
XmlSerializer xs = new XmlSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
XmlTextWriter xtw = new XmlTextWriter(ms, System.Text.Encoding.UTF8);
xtw.Formatting = Formatting.Indented;
xs.Serialize(xtw, obj);
ms.Seek(0, SeekOrigin.Begin);
StreamReader sr = new StreamReader(ms);
string str = sr.ReadToEnd();
xtw.Close();
ms.Close();
return str;
}
/// <summary>
/// 反序列化 从字符串
/// </summary>
/// <param name="xml">xml字符串</param>
/// <param name="type">要生成的对象类型</param>
/// <returns>反序列化后的对象</returns>
public static object Deserialize(string xml, Type type)
{
XmlSerializer xs = new XmlSerializer(type);
StringReader sr = new StringReader(xml);
object obj = xs.Deserialize(sr);
return obj;
}
public interface ObjectSerializer {
string Serialize<T>(T obj);
string Serialize(Type t, object obj);
T Deserialize<T>(string content);
object Deserialize(Type t, string content);
} public class JsonObjectSerializer : ObjectSerializer {
public string Serialize<T>(T obj) {
return Serialize(typeof(T), obj);
} public string Serialize(Type t, object obj) {
string result = string.Empty;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
using (MemoryStream ms = new MemoryStream()) {
serializer.WriteObject(ms, obj);
result = Encoding.UTF8.GetString(ms.ToArray());
}
return result;
} public T Deserialize<T>(string content) {
return (T)Deserialize(typeof(T), content);
} public object Deserialize(Type t, string content) {
object result = null;
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(content))) {
DataContractJsonSerializer serializer = new DataContractJsonSerializer(t);
result = serializer.ReadObject(ms);
}
return result;
}
} public class XmlObjectSerializer : ObjectSerializer {
public string Serialize<T>(T obj) {
return Serialize(typeof(T), obj);
} public string Serialize(Type t, object obj) {
StringBuilder result = new StringBuilder();
try {
XmlSerializer xs = new XmlSerializer(t);
xs.Serialize(new StringWriter(result), obj);
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
return result.ToString();
} public T Deserialize<T>(string content) {
return (T)Deserialize(typeof(T), content);
} public object Deserialize(Type t, string content) {
object result = null;
XmlSerializer xs = new XmlSerializer(t);
result = xs.Deserialize(new StringReader(content));
return result;
}
}
}
我不是反对自己做,只是一定要有意图,如果只是重复建设的话意义不大
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.Reflection;
using System.Xml;
using System.IO;
using System.Xml.Linq;namespace Richwork.Core
{
/// <summary>
/// 数据序列化
/// </summary>
/// <typeparam name="T"></typeparam>
public static class DataSerializer<T> where T:new()
{
/// <summary>
/// 对象属性克隆
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public static object CloneObject(object o)
{
Type t =o.GetType();
PropertyInfo[] properties =t.GetProperties();
object p =t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null);
foreach ( PropertyInfo pi in properties )
{
if ( pi.CanWrite )
{
object value=pi.GetValue(o, null);
pi.SetValue(p, value, null);
}
}
return p;
} #region //自定义优化加载XML
public static T LoadXML(string xml)
{
object obj = new T();
if ( xml == null ) return (T)obj;
if ( xml == string.Empty ) return (T)obj; System.IO.StringReader reader=new System.IO.StringReader(xml);
ObjectSerializer<T> ser=new ObjectSerializer<T>();
return (T)ser.Deserialize(reader, obj);
} public static string SaveXML(object obj)
{
if ( obj == null ) return ""; System.IO.StringWriter writer=new System.IO.StringWriter();
ObjectSerializer<T> ser = new ObjectSerializer<T>();
ser.Serialize(writer,obj);
return writer.ToString();
}
#endregion #region//String 序列化方式
public static string Save(object obj)
{
if ( obj == null ) return ""; System.IO.StringWriter writer=new System.IO.StringWriter();
XmlSerializer ser = new XmlSerializer(typeof(T));
ser.Serialize(writer, obj); return writer.ToString();
} public static T Load(string xml)
{
if ( xml == null ) return new T();
if ( xml == string.Empty ) return default(T); System.IO.StringReader reader=new System.IO.StringReader(xml); XmlSerializer ser=new XmlSerializer(typeof(T));
return (T)ser.Deserialize(reader); }
#endregion #region//byte[] 序列化方式
public static T LoadByte(byte[] xml)
{
if ( xml == null ) return new T();// default(T);
if ( xml.ToString() == string.Empty ) return default(T); System.IO.StringReader reader=new System.IO.StringReader(xml.ToString());//,System.Text.Encoding.UTF8); XmlSerializer ser=new XmlSerializer(typeof(T));
return (T)ser.Deserialize(reader);
} //Byte[]
public static byte[] SaveByte(object obj)
{
if ( obj == null ) return null; System.IO.StringWriter writer=new System.IO.StringWriter();
XmlSerializer ser = new XmlSerializer(typeof(T));
ser.Serialize(writer, obj); byte[] o=System.Text.Encoding.UTF8.GetBytes(writer.ToString());
return o; } #endregion }
/// <summary>
/// 对象序列化:
/// 由于需要提供个可以兼容的序列化工具
/// 开发目的:
/// 1.避免C#的序列化反序列化带来的成员变化的BUG。
/// 2.可以强制序列化只读具备【XMLWriter】的属性。
/// 3.避免WPF序列化子成员构建带来的子对象的依赖属性事件丢失的现象
/// 4.提供多个版本的兼容工具
/// 5.(Stream stream, object o),(TextWriter textWriter, object o);(XmlWriter xmlWriter, object o);
/// 特别注意:
/// 1.暂时不知泛型以及IList以及数组,需要扩展支持!!!!
/// </summary>
public class ObjectSerializer<T> where T : new()
{
private readonly string xmlns_prefix_xsi=@"http://www.w3.org/2001/XMLSchema-instance";//xmlns:xsi
private readonly string xmlns_prefix_xsd=@"http://www.w3.org/2001/XMLSchema";//xmlns:xsd /// <summary>
/// 不知何故,微软的Siverlight的Type的IsSerializable成了保护级别,无法访问。
/// 自己做一个判定是否可以序列化
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
private bool IsSerializable(Type t)
{
switch (Type.GetTypeCode(t))
{
case TypeCode.Object:
return false;
default:
return true;
}
} #region 序列化
public void Serialize(TextWriter textWriter, object o)
{
Serialize(o).Save(textWriter);
} public void Serialize(XmlWriter xmlWriter, object o)
{
Serialize(o).Save(xmlWriter);
} public void Serialize(Stream stream, object o)
{
Serialize(o).Save(stream);
} private XDocument Serialize(object o)
{
XDocument doc=new XDocument(new XComment("Richwork Framework 自定义生成"));
XElement element=new XElement(
o.GetType().Name,
new XAttribute(XNamespace.Xmlns+"xsi",xmlns_prefix_xsi),
new XAttribute(XNamespace.Xmlns+"xsd",xmlns_prefix_xsd)); SerializeProperty(o, element); doc.Add(element);
return doc;
} private void SerializeProperty(object o, XElement root)
{
Type t =o.GetType();
PropertyInfo[] properties =t.GetProperties(); foreach ( PropertyInfo pi in properties )//记录当前对象的成员
{
var Att = pi.GetCustomAttributes(typeof(XmlWriterAttribute), false).FirstOrDefault();//[i].GetCustomAttributes(true);Object[]
if ((pi.CanWrite) ||
(Att !=null))
{
object value=pi.GetValue(o, null);
if (IsSerializable(pi.PropertyType))
{
root.Add(new XElement(pi.Name,value));
}
else
{
XElement element=new XElement(pi.Name);
SerializeProperty(value, element);
root.Add(element);
}
} }
//return root;
} #endregion #region 反序列化
public T Deserialize(Stream stream,object o)
{
XDocument doc=XDocument.Load(stream);
return Deserialize(doc, o);
} public T Deserialize(TextReader textReader, object o)
{
XDocument doc=XDocument.Load(textReader);//未判断缺少根元素的错误,或者提供一个捕获错误的事件。
return Deserialize(doc, o);
} public T Deserialize(XmlReader xmlReader, object o)
{
XDocument doc=XDocument.Load(xmlReader);
return Deserialize(doc, o);
} private T Deserialize(XDocument doc, object o)
{
if ( o == null ) o = new T();//T o=new T();//object p =t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, null, o, null); XElement root=doc.Elements().FirstOrDefault();
if ( root != null )
o = DeserializeProperty(o, root);
return (T)o;
} private object DeserializeProperty(object o, XElement root)
{
Type t =o.GetType();
PropertyInfo[] properties =t.GetProperties(); foreach ( PropertyInfo pi in properties )
{
if ( pi.CanWrite )
{
if ( IsSerializable(pi.PropertyType))
{
XElement element=root.Elements().Where(p => p.Name.LocalName == pi.Name).FirstOrDefault();
//System.Diagnostics.Debug.WriteLine(element);
if ( element != null )
{
try
{
//根据属性的类型进行强制转换对应的类型,可能引发异常,未处理异常
object value=pi.GetValue(o, null);
pi.SetValue(o, Convert.ChangeType(element.Value, pi.PropertyType, null), null);
}
catch
{
pi.SetValue(o, null, null);//异常的是否,使用NULL,暂时这样处理
}
}
}
else //Class is
{
//XElement element=root.Elements().Where(p=>p.Name.Equals(pi.Name)).FirstOrDefault();
//==============
//XElement element=root.Elements().Where(p=>p.
XElement element=root.Elements().Where(p => p.Name.LocalName==pi.Name).FirstOrDefault(); if ( element != null )
{
object value=pi.GetValue(o, null);
DeserializeProperty(value,element); }
}
}//endif
}
//=============================
return o;
}
#endregion
}
}
/// 开发目的:
/// 1.避免C#的序列化反序列化带来的成员变化的BUG。
/// 2.可以强制序列化只读具备【XMLWriter】的属性。
/// 3.避免WPF序列化子成员构建带来的子对象的依赖属性事件丢失的现象
/// 4.提供多个版本的兼容工具
/// 5.(Stream stream, object o),(TextWriter textWriter, object o);(XmlWriter xmlWriter, object o);
/// 特别注意:
/// 1.暂时不知泛型以及IList以及数组,需要扩展支持!!!!
public static class JsonHelper
{
public static string ToJsonString<T>(T obj)
{
//Create a stream to serialize the object to.
MemoryStream ms = new MemoryStream(); // Serializer the User object to the stream.
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
ser.WriteObject(ms, obj);
byte[] json = ms.ToArray();
ms.Close();
return Encoding.UTF8.GetString(json, 0, json.Length);
} public static T FromJsonString<T>(string jsonString)
{
T desrializedObject = default(T);
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
desrializedObject = (T)ser.ReadObject(ms);
ms.Close();
return desrializedObject;
}
}
基本上json就足够。