JSON格式序列化与反序列化(List、XML)
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.Serialization.Json; using System.Xml.Serialization; using System.Web.Script.Serialization; namespace Common { public class JsonHelper { /// <summary> /// 序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string GetJson<T>(T obj) { if (obj == null) return null; DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, obj); return Encoding.UTF8.GetString(stream.ToArray(), 0, stream.ToArray().Length); } } /// <summary> /// 反序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="szJson"></param> /// <returns></returns> public static T ParseFromJson<T>(string szJson) { if (string.IsNullOrEmpty(szJson)) return default(T);
//xml内容乱码可正确转换 using (var ms = JsonReaderWriterFactory.CreateJsonReader(Encoding.UTF8.GetBytes(szJson), XmlDictionaryReaderQuotas.Max)) using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) { var serializer = new DataContractJsonSerializer(typeof(T)); return (T)serializer.ReadObject(ms); } } /// <summary> /// 对未知或匿名对象进行Json序列化。 /// </summary> /// <param name="value"></param> /// <returns></returns> public static string GetUnknownJson(object value) { if (value == null) return null; return new JavaScriptSerializer().Serialize(value); } /// <summary> /// DataContractJson序列化,用于序列化里面附带未知类型的实体。 /// </summary> /// <param name="value"></param> /// <param name="knownTypes">知道类型</param> /// <returns></returns> public static string GetJson(object value, IEnumerable<Type> knownTypes) { if (value == null) return null; using (var ms = new MemoryStream()) { new DataContractJsonSerializer(value.GetType(), knownTypes).WriteObject(ms, value); return Encoding.UTF8.GetString(ms.ToArray()); } } #region 序列化文件和反序列化 /// <summary> /// 通用类的保存函数,可以将已经声明过可序列化的类以文件方式保存起来。 /// 保存格式分为 XML明文式和 二进制。 /// 如果目标目录不存在,就自动创建目录。 /// </summary> /// <typeparam name="T">要保存的类的类型</typeparam> /// <param name="tclass">要保存的类</param> /// <param name="sFilePath">要保存的文件完整路径,包括文件名。</param> /// <param name="bXmlOrBin">true=XML,false=Bin</param> /// <exception cref="System.Exception"></exception> public void Save<T>(T tclass, string sFilePath, bool bXmlOrBin) { //目录检查 string sFolder = sFilePath.Substring(0, sFilePath.LastIndexOf("\\")); if (!Directory.Exists(sFolder)) Directory.CreateDirectory(sFolder); using (FileStream fs = new FileStream(sFilePath, FileMode.Create, FileAccess.Write)) { if (bXmlOrBin) { using (MemoryStream stream = Serialize<T>(tclass, bXmlOrBin)) { stream.WriteTo(fs); stream.Close(); } } else { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = null; bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(fs, bXmlOrBin); } fs.Close(); } } /// <summary> /// 从文件加载保存的信息,然后反序列化并返回保存的信息。 /// 如果要读取的文件不存在会引发异常。 /// </summary> /// <typeparam name="T">类型</typeparam> /// <param name="tclass">要返回的类,失败返回默认</param> /// <param name="sFilePath">文件路径</param> /// <param name="bXmlOrBin">true=XML,false=Bin</param> /// <exception cref="System.Exception"></exception> /// <exception cref="System.IO.IOException">文件不存在</exception> public void Load<T>(out T tclass, string sFilePath, bool bXmlOrBin) { if (!File.Exists(sFilePath)) { tclass = default(T); return; //throw new IOException("要访问的文件不存在。"); } using (FileStream fs = new FileStream(sFilePath, FileMode.Open, FileAccess.Read)) { tclass = Deserialize<T>(fs, bXmlOrBin); fs.Close(); } } /// <summary> /// 将传入的某个模型序列化,并返回其数据量,用于保存到文件里面。 /// 提供序列化到XML或二进制。 /// </summary> /// <typeparam name="T">类的类型</typeparam> /// <param name="model">要序列化的模型</param> /// <param name="bXmlOrBin">true=xml序列化,false=二进制序列化</param> /// <returns></returns> /// <exception cref="System.Exception"></exception> public MemoryStream Serialize<T>(T model, bool bXmlOrBin = true) { MemoryStream stream = new MemoryStream(); if (bXmlOrBin) { XmlSerializer serializer = new XmlSerializer(typeof(T)); serializer.Serialize(stream, model); } else { var bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); bf.Serialize(stream, model); } stream.Position = 0; return stream; } /// <summary> /// 将传入的数据量进行反序列化。 /// </summary> /// <typeparam name="T">类的类型</typeparam> /// <param name="stream">要反序列化的流</param> /// <param name="bXmlOrBin">true=xml序列化,false=二进制序列化</param> /// <returns></returns> public T Deserialize<T>(Stream stream, bool bXmlOrBin = true) { T model = default(T); using (var newstream = stream) { if (bXmlOrBin) { XmlSerializer serializer = new XmlSerializer(typeof(T)); //暂时没做什么处理,以后有日志文件,就直接添加进入 serializer.UnknownNode += new XmlNodeEventHandler(serializer_UnknownNode); serializer.UnknownAttribute += new XmlAttributeEventHandler(serializer_UnknownAttribute); model = (T)serializer.Deserialize(newstream); } else { System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = null; bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); model = (T)bf.Deserialize(newstream); } } return model; } #region 反序列化中出错的问题 private void serializer_UnknownNode(object sender, XmlNodeEventArgs e) { string aaaa = "Unknown Node:" + e.Name + "\t" + e.Text; string bb = string.Empty; } private void serializer_UnknownAttribute(object sender, XmlAttributeEventArgs e) { System.Xml.XmlAttribute attr = e.Attr; string aaaa = "Unknown attribute " + attr.Name + "='" + attr.Value + "'"; string bb = string.Empty; } #endregion #endregion } }
/// <summary> /// DataGrid数据的序列化 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static string GetDataGridJson<T>(T obj, int total) { StringBuilder strJson = new StringBuilder(); if (obj != null) { DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, obj); strJson.Append("{ "); strJson.Append("\"rows\":"); strJson.Append(Encoding.UTF8.GetString(stream.ToArray(), 0, stream.ToArray().Length)); strJson.Append(","); strJson.Append("\"total\":"); strJson.Append(total); strJson.Append("}"); } return strJson.ToString(); } else { return "{ \"rows\":[],\"total\":0}"; } } /// <summary> /// 将json字符串转成list对象 /// </summary> /// <param name="JsonStr">json串</param> /// <returns></returns> public static List<T> JSONStringToList<T>(string JsonStr) { JavaScriptSerializer Serializer = new JavaScriptSerializer(); List<T> objs = Serializer.Deserialize<List<T>>(JsonStr); return objs; }
调用方式:
//序列化 转换数据至JSON格式
string strData = JsonHelper.GetJson<List<string>>(listLHCode);//包括List对象集合 <List<T_Users>>
//反序列化
List<T_Users> dataList = JsonHelper.ParseFromJson<List<T_Users>>(sRtdData);
//未知对象转JSON格式
string strData = JsonHelper.GetUnknownJson(new { Channel = Channel, IP = IP })
引用:
首先添加System.Runtime.Serialization的引用
/*对象转json字符(Kafka)*/ var args = new Dictionary<string, string> { { "datas", JsonHelper.GetJson<List<WaterRealTimeData>>(listRealData) } , { "username", "cn" } , { "password", "cn" } }; var jsonString = JsonConvert.SerializeObject(args, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });