c#的序列化与反序列化

时间:2022-05-06 15:00:55

这是反序列化的代码

using System.Runtime.Serialization.Json;

   public  static T deserialize<T>(String s)
{
//JSON反序列化
byte[] buf = Encoding.UTF8.GetBytes(s);
MemoryStream ms = new MemoryStream(buf);
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
return (T)json.ReadObject(ms);
}

序列化

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

        static String serialize(OrderList s)
{
//Json序列化 Object --> Json String
//DataContrctJsonSerializer类
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(OrderList));
//内存数据流
MemoryStream ms = new MemoryStream();
//序列化到内存数据流
json.WriteObject(ms, s);
//变成数组
byte[] buf = ms.ToArray();
//转为UTF8字符串
return Encoding.UTF8.GetString(buf); }

还有一种一样序列化

  String serialize<T>(T obj) {
DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
json.WriteObject(ms, obj);
byte[] buf = ms.ToArray();
return Encoding.UTF8.GetString(buf);

为了方便随时调用