物件和XML,JSON格式字串的相互轉換
阿新 • • 發佈:2019-01-30
- 物件和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; } }