一次作到一個關於使用DataContractJsonSerializer類的表述。其中須要用到MemoryStream數組讀取。發生數組溢出錯誤,這裏特記錄一筆:json
public static class JsonSerializer<T> where T:new() { public static string Serialize(T obj) { string json = null; using (MemoryStream ms = new MemoryStream()) { try { DataContractJsonSerializer jsonS = new DataContractJsonSerializer(typeof(T)); jsonS.WriteObject(ms, obj); ms.Position = 0; // 總的要讀入的字節數數組 byte[] bytes = new byte[ms.Length]; // 讀取數據的起始點 int offset = 0; // 判斷起始點+偏移量的數據必須在數組總的範圍內 while (offset+10<ms.Length) { // 嘗試讀取後10個數據 ms.Read(bytes, offset, 10); // 起始點+10 offset += 10; } //剩餘的數組所有讀完 if (offset + 10 >= ms.Length) { ms.Read(bytes, offset, (int)(ms.Length - offset)); } json = Encoding.UTF8.GetString(bytes); } catch (Exception ex) { } } return json; } public static T Deserialize(string json) { T returnValue = default(T); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { ms.Position = 0; DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(T)); returnValue = (T)ds.ReadObject(ms); } return returnValue; } }