using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StreamTest { public class JsonSerialization { #region Serialize/Deserialize public static string Serialize<T>(object obj) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, obj); return Encoding.UTF8.GetString(ms.ToArray()); } } public static T Deserialize<T>(string input) { if (string.IsNullOrWhiteSpace(input)) { return default(T); } DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(input))) { return (T)serializer.ReadObject(ms); } } #endregion } }
时间: 2024-10-08 18:27:18