// This is the object that will be serialized and deserialized.
[Serializable()]
public class TestSimpleObject
{
// This member is serialized and deserialized with no change.
public int member1;
// The value of this field is set and reset during and
// after serialization.
private string member2;
// This field is not serialized. The OnDeserializedAttribute
// is used to set the member value after serialization.
[NonSerialized()]
public string member3;
// This field is set to null, but populated after deserialization.
private string member4;
// Constructor for the class.
public TestSimpleObject()
{
member1 = 11;
member2 = "Hello World!";
member3 = "This is a nonserialized value";
member4 = null;
}
public void Print()
{
Console.WriteLine("member1 = '{0}'", member1);
Console.WriteLine("member2 = '{0}'", member2);
Console.WriteLine("member3 = '{0}'", member3);
Console.WriteLine("member4 = '{0}'", member4);
}
[OnSerializing()]
internal void OnSerializingMethod(StreamingContext context)
{
member2 = "This value went into the data file during serialization.";
}
[OnSerialized()]
internal void OnSerializedMethod(StreamingContext context)
{
member2 = "This value was reset after serialization.";
}
[OnDeserializing()]
internal void OnDeserializingMethod(StreamingContext context)
{
member3 = "This value was set during deserialization";
}
[OnDeserialized()]
internal void OnDeserializedMethod(StreamingContext context)
{
member4 = "This value was set after deserialization.";
}
}
[Serializable]
public class MyObject : ISerializable
{
public int n1;
public int n2;
public String str;
public MyObject()
{
}
protected MyObject(SerializationInfo info, StreamingContext context)
{
n1 = info.GetInt32("i");
n2 = info.GetInt32("j");
str = info.GetString("k");
}
[SecurityPermissionAttribute(SecurityAction.Demand,SerializationFormatter
=true)]
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("i", n1);
info.AddValue("j", n2);
info.AddValue("k", str);
}
}
public class MyClass
{
public MyObject MyObjectProperty;
}
public class MyObject
{
public string ObjectName;
}
<MyClass> <MyObjectProperty> <ObjectName>My String</ObjectName> </MyObjectProperty> </MyClass>
namespace DataContractSerializerExample
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml;
// You must apply a DataContractAttribute or SerializableAttribute
// to a class to have it serialized by the DataContractSerializer.
[DataContract(Name = "Customer", Namespace = "http://www.contoso.com")]
class Person : IExtensibleDataObject
{
[DataMember()]
public string FirstName;
[DataMember]
public string LastName;
[DataMember()]
public int ID;
public Person(string newfName, string newLName, int newID)
{
FirstName = newfName;
LastName = newLName;
ID = newID;
}
private ExtensionDataObject extensionData_Value;
public ExtensionDataObject ExtensionData
{
get
{
return extensionData_Value;
}
set
{
extensionData_Value = value;
}
}
}
public sealed class Test
{
private Test() { }
public static void Main()
{
try
{
WriteObject("DataContractSerializerExample.xml");
ReadObject("DataContractSerializerExample.xml");
}
catch (SerializationException serExc)
{
Console.WriteLine("Serialization Failed");
Console.WriteLine(serExc.Message);
}
catch (Exception exc)
{
Console.WriteLine(
"The serialization operation failed: {0} StackTrace: {1}",
exc.Message, exc.StackTrace);
}
finally
{
Console.WriteLine("Press <Enter> to exit....");
Console.ReadLine();
}
}
public static void WriteObject(string fileName)
{
Console.WriteLine(
"Creating a Person object and serializing it.");
Person p1 = new Person("Zighetti", "Barbara", 101);
FileStream writer = new FileStream(fileName, FileMode.Create);
DataContractSerializer ser =
new DataContractSerializer(typeof(Person));
ser.WriteObject(writer, p1);
writer.Close();
}
public static void ReadObject(string fileName)
{
Console.WriteLine("Deserializing an instance of the object.");
FileStream fs = new FileStream(fileName,
FileMode.Open);
XmlDictionaryReader reader =
XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());
DataContractSerializer ser = new DataContractSerializer(typeof(Person));
// Deserialize the data and read it from the instance.
Person deserializedPerson =
(Person)ser.ReadObject(reader, true);
reader.Close();
fs.Close();
Console.WriteLine(String.Format("{0} {1}, ID: {2}",
deserializedPerson.FirstName, deserializedPerson.LastName,
deserializedPerson.ID));
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.Xml.Serialization;
namespace SerializerSample
{
/// <summary>
/// 序列化帮助类
/// </summary>
public sealed class SerializeHelper
{
#region DataContract序列化
/// <summary>
/// DataContract序列化
/// </summary>
/// <param name="value"></param>
/// <param name="knownTypes"></param>
/// <returns></returns>
public static string SerializeDataContract(object value, List<Type> knownTypes = null)
{
DataContractSerializer dataContractSerializer = new DataContractSerializer(value.GetType(), knownTypes);
using (MemoryStream ms = new MemoryStream())
{
dataContractSerializer.WriteObject(ms, value);
ms.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new StreamReader(ms))
{
return sr.ReadToEnd();
}
}
}
/// <summary>
/// DataContract反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="xml"></param>
/// <returns></returns>
public static T DeserializeDataContract<T>(string xml)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
#endregion
#region DataContractJson序列化
/// <summary>
/// DataContractJson序列化
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string SerializeDataContractJson(object value)
{
DataContractJsonSerializer dataContractSerializer = new DataContractJsonSerializer(value.GetType());
using (MemoryStream ms = new MemoryStream())
{
dataContractSerializer.WriteObject(ms, value);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
/// <summary>
/// DataContractJson反序列化
/// </summary>
/// <param name="type"></param>
/// <param name="str"></param>
/// <returns></returns>
public static object DeserializeDataContractJson(Type type, string str)
{
DataContractJsonSerializer dataContractSerializer = new DataContractJsonSerializer(type);
using (MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(str)))
{
return dataContractSerializer.ReadObject(ms);
}
}
/// <summary>
/// DataContractJson反序列化
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="json"></param>
/// <returns></returns>
public T DeserializeDataContractJson<T>(string json)
{
DataContractJsonSerializer dataContractSerializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return (T)dataContractSerializer.ReadObject(ms);
}
}
#endregion
#region XmlSerializer序列化
/// <summary>
/// 将对象序列化到 XML 文档中和从 XML 文档中反序列化对象。XmlSerializer 使您得以控制如何将对象编码到 XML 中。
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static string SerializeXml(object value)
{
XmlSerializer serializer = new XmlSerializer(value.GetType());
using (MemoryStream ms = new MemoryStream())
{
serializer.Serialize(ms, value);
ms.Seek(0, SeekOrigin.Begin);
using (StreamReader sr = new StreamReader(ms))
{
return sr.ReadToEnd();
}
}
}
/// <summary>
/// XmlSerializer反序列化
/// </summary>
/// <param name="type"></param>
/// <param name="str"></param>
/// <returns></returns>
public static object DeserializeXml(Type type, string str)
{
XmlSerializer serializer = new XmlSerializer(type);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
using (MemoryStream ms = new MemoryStream(bytes))
{
return serializer.Deserialize(ms);
}
}
#endregion
#region BinaryFormatter序列化
/// <summary>
/// BinaryFormatter序列化
/// 必须类型必须标记为Serializable
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string SerializeBinaryFormatter(object obj)
{
BinaryFormatter formatter = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
formatter.Serialize(ms,obj);
byte[] bytes = ms.ToArray();
obj = formatter.Deserialize(new MemoryStream(bytes));
//如果是UTF8格式,则反序列化报错。可以用Default格式,不过,建议还是传参为byte数组比较好
return Encoding.Default.GetString(bytes);
}
}
/// <summary>
/// BinaryFormatter反序列化
/// 必须类型必须标记为Serializable
/// </summary>
/// <param name="serializedStr"></param>
/// <returns></returns>
public static T DeserializeBinaryFormatter<T>(string serializedStr)
{
BinaryFormatter formatter = new BinaryFormatter();
byte[] bytes = Encoding.Default.GetBytes(serializedStr);
using (MemoryStream ms = new MemoryStream(bytes))
{
return (T)formatter.Deserialize(ms);
}
}
#endregion
#region SoapFormatter序列化
/// <summary>
/// SoapFormatter序列化
/// 必须类型必须标记为Serializable
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static string SerializeSoapFormatter(object obj)
{
SoapFormatter formatter = new SoapFormatter();
using (MemoryStream ms = new MemoryStream())
{
formatter.Serialize(ms, obj);
byte[] bytes = ms.ToArray();
return Encoding.UTF8.GetString(bytes);
}
}
/// <summary>
/// SoapFormatter反序列化
/// 必须类型必须标记为Serializable
/// </summary>
/// <param name="serializedStr"></param>
/// <returns></returns>
public static T DeserializeSoapFormatter<T>(string serializedStr)
{
SoapFormatter formatter = new SoapFormatter();
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(serializedStr)))
{
return (T)formatter.Deserialize(ms);
}
}
#endregion
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有