你的位置:首页 > ASP.net教程

[ASP.net教程]c#的序列化与反序列化


这是反序列化的代码

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); }

为了方便随时调用