第五回 C#之序列化
序列化:将实例转换成字符串
反序列化:将字符串转换成实例
public static T Deserialize<T>(this string jsonString, Encoding encoding) where T : class, new()
{
T result;
try
{
//内存流
using (MemoryStream memoryStream = new MemoryStream(encoding.GetBytes(jsonString)))
{
result = (T)(new DataContractJsonSerializer(typeof(T)).ReadObject(memoryStream));
}
}
catch (Exception)
{
result = default(T);
}
return result;
}
////////////////////
public static string Serialize(this object jsonObject, Encoding encoding)
{
string str;
try
{
using (MemoryStream memoryStream = new MemoryStream())
{
Type type = jsonObject.GetType();
new DataContractJsonSerializer(type).WriteObject(memoryStream, jsonObject);
str = encoding.GetString(memoryStream.ToArray(), 0, memoryStream.ToArray().Length);
}
}
catch (Exception)
{
throw;
}
return str;
}