- 对象和Json格式数据互转。这里用到了JSON.NET(Newtonsoft.json)需要应用外部dll,可自行下载
/// <summary> /// 把对象序列化 JSON 字符串 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="obj">对象实体</param> /// <returns>JSON字符串</returns> public static string ToJsonString<T>(this T obj) { var json = new DataContractJsonSerializer(typeof(T)); using (var ms = new MemoryStream()) { json.WriteObject(ms,obj); string szJson = Encoding.UTF8.GetString(ms.ToArray()); return szJson; } } /// <summary> /// 把JSON字符串还原为对象 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="szJson">JSON字符串</param> /// <returns>对象实体</returns> public static T ParseFormJson<T>(this string szJson) { T obj = Activator.CreateInstance<T>(); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) { var dcj = new DataContractJsonSerializer(typeof(T)); return (T)dcj.ReadObject(ms); } }
- 对象和xml格式字符串互转。as作用:强制转换为引用类型,所以T要限制为class。
/// <summary> /// 把对象转换为XML字符串 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="obj">对象实体</param> /// <returns>xml格式的字符串</returns> public static string ToXmlString<T>(this T obj) { string xmlString; var xmlSerializer = new XmlSerializer(typeof(T)); using (var ms = new MemoryStream()) { var streamWriter = new StreamWriter(ms); xmlSerializer.Serialize(streamWriter,obj); xmlString = Encoding.UTF8.GetString(ms.ToArray()); } return xmlString; } /// <summary> /// 把XML格式的字符串还原为对象 /// </summary> /// <typeparam name="T">对象类型</typeparam> /// <param name="xml">xml格式字符串</param> /// <returns>对象实体</returns> public static T XmlToObject<T>(this string xml) where T : class { var xmlSerializer = new XmlSerializer(typeof(T)); using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(xml))) { return xmlSerializer.Deserialize(ms) as T; } }