這是反序列化的代碼
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); }
為了方便隨時調用