.net core 对象序列化为Json及Json反序列化关于DataContractJsonSerializer和Newtonsoft使用的完整案例,源码已更新至开源模板
殷慈航 人气:1很多人告诉你怎么用,但是却不会告诉你用什么好。不知道在进行序列化和反序列化Json时用那个好,因为有太多选择,如.NET Framework下可以选DataContractJsonSerializer、JavaScriptSerializer、Newtonsoft.Json,但是JavaScriptSerializer在.net core下已经没有了,那么大家还有两种选择DataContractJsonSerializer和Newtonsoft.Json,因为这两个都有人用,所以我做了完整的对象转换demo进行了测试,这里我不仅和大家讲如何使用,并且还把我自己写的参与测试并告诉各位怎么测试的。
为了节约开发时间,我们把解决方案收入到一个个demo中,方便以后即拿即用。而且这些demo有博客文档支持,帮助任何人非常容易上手开发跨平台的.net core。随着时间的推移,我们的demo库会日益强大请及时收藏GitHub。
好了在讲序列化及反序列化之前先把我们的测试结果分享给大家,十万数据测速比较告诉你为何用Newtonsoft。
一、首先在Common公用项目中引用Newtonsoft的类库
Install-Package Newtonsoft.Json -Version 12.0.3-beta2
二、在Common公用项目中添加CommonHelper
#region model<->json(对象和json互转) #region DataContractJsonSerializer public static string SerializeDataContractJson<T>(T obj) { DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, obj); string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson; } } public static T DeserializeDataContractJson<T>(string szJson) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); return (T)serializer.ReadObject(ms); } } #endregion #region Newtonsoft static public string SerializeJSON<T>(T data) { return Newtonsoft.Json.JsonConvert.SerializeObject(data); } static public T DeserializeJSON<T>(string json) { return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json); } #endregion #endregion #region datatable<->json(datatable和json互转) public static string SerializeDataTableToJSON(DataTable dt) { return Newtonsoft.Json.JsonConvert.SerializeObject(dt); } public static DataTable SerializeJSONToDataTable(string json) { return Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>(json); } #region 自己写datatable转json用于测试速度对比下 public static string MyDataTableToJson(DataTable dt) { StringBuilder JsonString = new StringBuilder(); if (dt != null && dt.Rows.Count > 0) { JsonString.Append("{ "); JsonString.Append("\"TableInfo\":[ "); for (int i = 0; i < dt.Rows.Count; i++) { JsonString.Append("{ "); for (int j = 0; j < dt.Columns.Count; j++) { if (j < dt.Columns.Count - 1) { JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\","); } else if (j == dt.Columns.Count - 1) { JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\""); } } if (i == dt.Rows.Count - 1) { JsonString.Append("} "); } else { JsonString.Append("}, "); } } JsonString.Append("]}"); return JsonString.ToString(); } else { return null; } } #endregion #endregion
三、控制器添加Json处理相应方法(我这里整合所有到了HomeController下的Json中了,你们不需要计时,用的时候只需要调用CommonHelper的相关方法即可)
public IActionResult Json() { List<Article> articleList = new List<Article>(); for (int x = 0; x < 100000; x++) { Article article = new Article(); article.Context = "内容:" + x; article.Id = x + 1; article.CreateTime = DateTime.Now; article.Title = "标题:" + x; articleList.Add(article); } #region 单个对象与json互转 Article articletest = new Article(); articletest.Context = "内容"; articletest.Id = 1; articletest.CreateTime = DateTime.Now; articletest.Title = "标题"; string json11 = CommonHelper.SerializeDataContractJson(articletest); string json12 = CommonHelper.SerializeJSON(articletest); Article article1 = CommonHelper.DeserializeDataContractJson<Article>(json11); Article article2 = CommonHelper.DeserializeJSON<Article>(json12); #endregion #region 记录10万对象集合与json互转用时比较 //SerializeDataContractJson 10万对象转json System.Diagnostics.Stopwatch watch1 = new System.Diagnostics.Stopwatch(); watch1.Start(); //开始监视代码运行时间 string json1 = CommonHelper.SerializeDataContractJson(articleList); TimeSpan timespan1 = watch1.Elapsed; //获取当前实例测量得出的总时间 watch1.Stop(); //停止监视 ViewBag.t1= timespan1.TotalSeconds; //Newtonsoft 10万对象转json System.Diagnostics.Stopwatch watch2 = new System.Diagnostics.Stopwatch(); watch2.Start(); string json2 = CommonHelper.SerializeJSON(articleList); TimeSpan timespan2 = watch2.Elapsed; watch2.Stop(); ViewBag.t2 = timespan2.TotalSeconds; //SerializeDataContractJson 10万json转对象 System.Diagnostics.Stopwatch watch3 = new System.Diagnostics.Stopwatch(); watch3.Start(); List<Article> list1 = CommonHelper.DeserializeDataContractJson<List<Article>>(json1); TimeSpan timespan3 = watch3.Elapsed; watch3.Stop(); ViewBag.t3 = timespan3.TotalSeconds; //Newtonsoft 10万json转对象 System.Diagnostics.Stopwatch watch4 = new System.Diagnostics.Stopwatch(); watch4.Start(); List<Article> list2 = CommonHelper.DeserializeJSON<List<Article>>(json2); TimeSpan timespan4 = watch4.Elapsed; watch4.Stop(); ViewBag.t4 = timespan4.TotalSeconds; #endregion #region 记录10万datatable与json互转用时比较 DataTable tblDatas = new DataTable("Datas"); DataColumn dc = null; dc = tblDatas.Columns.Add("ID", Type.GetType("System.Int32")); dc.AutoIncrement = true;//自动增加 dc.AutoIncrementSeed = 1;//起始为1 dc.AutoIncrementStep = 1;//步长为1 dc.AllowDBNull = false;// dc = tblDatas.Columns.Add("Product", Type.GetType("System.String")); dc = tblDatas.Columns.Add("Version", Type.GetType("System.String")); dc = tblDatas.Columns.Add("Description", Type.GetType("System.String")); for (int x = 0; x < 100000; x++) { DataRow newRow = tblDatas.NewRow(); newRow["Product"] = "西游记" + x; newRow["Version"] = "" + x; newRow["Description"] = x; tblDatas.Rows.Add(newRow); } //Newtonsoft 10万DataTable转json System.Diagnostics.Stopwatch watch5 = new System.Diagnostics.Stopwatch(); watch5.Start(); string json5 = CommonHelper.SerializeDataTableToJSON(tblDatas); TimeSpan timespan5 = watch5.Elapsed; watch5.Stop(); ViewBag.t5 = timespan5.TotalSeconds; //Newtonsoft 10万json转DataTable System.Diagnostics.Stopwatch watch6 = new System.Diagnostics.Stopwatch(); watch6.Start(); DataTable dataTable = CommonHelper.SerializeJSONToDataTable(json5); TimeSpan timespan6 = watch6.Elapsed; watch6.Stop(); ViewBag.t6 = timespan6.TotalSeconds; //自己写的 10万DataTable转json System.Diagnostics.Stopwatch watch7 = new System.Diagnostics.Stopwatch(); watch7.Start(); string json7 = CommonHelper.MyDataTableToJson(tblDatas); TimeSpan timespan7 = watch7.Elapsed; watch7.Stop(); ViewBag.t7 = timespan7.TotalSeconds; #endregion return View(); }
四、前端设计(这里也没啥设计了,只是做了展示,代码我还是贴出来吧)
<div style="width:80%;margin:auto;text-align:center;"> <div class="cover" style="border: 1px solid #D6D6D6;padding: 5px;"> <h2>10万对象与json互转</h2> <span>SerializeDataContractJson:对象集合转json(@ViewBag.t1 秒),json转对象集合(@ViewBag.t3 秒)</span><br /> <span>Newtonsoft:对象集合转json(@ViewBag.t2 秒),json转对象集合(@ViewBag.t4 秒)</span> </div> <div class="cover" style="border: 1px solid #D6D6D6;padding: 5px;"> <h2>10万datatable与json互转</h2> <span>Newtonsoft:datatable转json(@ViewBag.t5 秒),json转datatable(@ViewBag.t6 秒)</span><br /> <span>自己码:datatable转json(@ViewBag.t7 秒)</span> </div> </div>
五、那么看下效果吧。
开源地址 动动小手,点个推荐吧!
注意:我们机遇屋该项目将长期为大家提供asp.net core各种好用demo,旨在帮助.net开发者提升竞争力和开发速度,建议尽早收藏该模板集合项目。
加载全部内容