C#中JavaScriptSerializer幫助類用法例項
這篇文章主要介紹了C#中JavaScriptSerializer幫助類用法,例項分析了JavaScriptSerializer幫助類處理json字串時的技巧,需要的朋友可以參考下
本文例項講述了C#中JavaScriptSerializer幫助類用法。分享給大家供大家參考。具體如下:
關鍵程式碼如下:
複製程式碼程式碼如下:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
namespace YanZhiwei.DotNet3._5.Utilities.Common
{
/// <summary>
/// JavaScriptSerializer 幫助類
/// </summary>
public static class ScriptSerializerHelper
{
#region 處理Json字串的時間格式問題
/// <summary>
/// 處理JsonString的時間格式問題
/// <para>eg:ScriptSerializerHelper.ParseJsonTime(@"[{'getTime':'\/Date(1419564257428)\/'}]", "yyyyMMdd hh:mm:ss");==>[{'getTime':'20141226 11:24:17'}]</para>
/// <para>參考:http://www.cnphp6.com/archives/35773 </para>
/// </summary>
/// <param name="jsonString">Json字串</param>
/// <param name="formart">時間格式化型別</param>
/// <returns>處理好的Json字串</returns>
public static string ParseJsonTime(this string jsonString, string formart)
{
if (!string.IsNullOrEmpty(jsonString))
{
jsonString = Regex.Replace(jsonString, @"\\/Date\((\d+)\)\\/", match =>
{
DateTime _dateTime = new DateTime(1970, 1, 1);
_dateTime = _dateTime.AddMilliseconds(long.Parse(match.Groups[1].Value));
_dateTime = _dateTime.ToLocalTime();
return _dateTime.ToString(formart);
});
}
return jsonString;
}
/// <summary>
/// 處理JsonString的時間格式問題【時間格式:yyyy-MM-dd HH:mm:ss】
/// <para>參考:http://www.cnphp6.com/archives/35773 </para>
/// </summary>
/// <param name="jsonString">Json字串</param>
/// <returns>處理好的Json字串</returns>
public static string ParseJsonTime(this string jsonString)
{
return ParseJsonTime(jsonString, "yyyy-MM-dd HH:mm:ss");
}
#endregion
#region 利用JavaScriptSerializer將物件序列化成JSON
/// <summary>
/// 利用JavaScriptSerializer將物件序列化成JSON字串
/// <para>eg:ScriptSerializerHelper.Serialize<Person>(_personList);</para>
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="entityList">物件集合</param>
/// <returns>json</returns>
public static string Serialize<T>(this IEnumerable<T> entityList) where T : class
{
string _jsonString = string.Empty;
if (entityList != null)
{
JavaScriptSerializer _serializerHelper = new JavaScriptSerializer();
_serializerHelper.MaxJsonLength = int.MaxValue;
_jsonString = _serializerHelper.Serialize(entityList);
}
return _jsonString;
}
#endregion
#region 利用JavaScriptSerializer將json字串反序列化
/// <summary>
///利用JavaScriptSerializer將json字串反序列化
/// <para>eg:List<Person> _result = (List<Person>)ScriptSerializerHelper.Deserialize<Person>(_jsonString);</para>
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="jsonString"></param>
/// <returns>IEnumerable</returns>
public static IEnumerable<T> Deserialize<T>(this string jsonString) where T : class
{
IEnumerable<T> _list = null;
if (!string.IsNullOrEmpty(jsonString))
{
JavaScriptSerializer _serializerHelper = new JavaScriptSerializer();
_list = _serializerHelper.Deserialize<IEnumerable<T>>(jsonString);
}
return _list;
}
#endregion
}
}
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
namespace YanZhiwei.DotNet3._5.Utilities.Common
{
/// <summary>
/// JavaScriptSerializer 幫助類
/// </summary>
public static class ScriptSerializerHelper
{
#region 處理Json字串的時間格式問題
/// <summary>
/// 處理JsonString的時間格式問題
/// <para>eg:ScriptSerializerHelper.ParseJsonTime(@"[{'getTime':'\/Date(1419564257428)\/'}]", "yyyyMMdd hh:mm:ss");==>[{'getTime':'20141226 11:24:17'}]</para>
/// <para>參考:http://www.cnphp6.com/archives/35773 </para>
/// </summary>
/// <param name="jsonString">Json字串</param>
/// <param name="formart">時間格式化型別</param>
/// <returns>處理好的Json字串</returns>
public static string ParseJsonTime(this string jsonString, string formart)
{
if (!string.IsNullOrEmpty(jsonString))
{
jsonString = Regex.Replace(jsonString, @"\\/Date\((\d+)\)\\/", match =>
{
DateTime _dateTime = new DateTime(1970, 1, 1);
_dateTime = _dateTime.AddMilliseconds(long.Parse(match.Groups[1].Value));
_dateTime = _dateTime.ToLocalTime();
return _dateTime.ToString(formart);
});
}
return jsonString;
}
/// <summary>
/// 處理JsonString的時間格式問題【時間格式:yyyy-MM-dd HH:mm:ss】
/// <para>參考:http://www.cnphp6.com/archives/35773 </para>
/// </summary>
/// <param name="jsonString">Json字串</param>
/// <returns>處理好的Json字串</returns>
public static string ParseJsonTime(this string jsonString)
{
return ParseJsonTime(jsonString, "yyyy-MM-dd HH:mm:ss");
}
#endregion
#region 利用JavaScriptSerializer將物件序列化成JSON
/// <summary>
/// 利用JavaScriptSerializer將物件序列化成JSON字串
/// <para>eg:ScriptSerializerHelper.Serialize<Person>(_personList);</para>
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="entityList">物件集合</param>
/// <returns>json</returns>
public static string Serialize<T>(this IEnumerable<T> entityList) where T : class
{
string _jsonString = string.Empty;
if (entityList != null)
{
JavaScriptSerializer _serializerHelper = new JavaScriptSerializer();
_serializerHelper.MaxJsonLength = int.MaxValue;
_jsonString = _serializerHelper.Serialize(entityList);
}
return _jsonString;
}
#endregion
#region 利用JavaScriptSerializer將json字串反序列化
/// <summary>
///利用JavaScriptSerializer將json字串反序列化
/// <para>eg:List<Person> _result = (List<Person>)ScriptSerializerHelper.Deserialize<Person>(_jsonString);</para>
/// </summary>
/// <typeparam name="T">泛型</typeparam>
/// <param name="jsonString"></param>
/// <returns>IEnumerable</returns>
public static IEnumerable<T> Deserialize<T>(this string jsonString) where T : class
{
IEnumerable<T> _list = null;
if (!string.IsNullOrEmpty(jsonString))
{
JavaScriptSerializer _serializerHelper = new JavaScriptSerializer();
_list = _serializerHelper.Deserialize<IEnumerable<T>>(jsonString);
}
return _list;
}
#endregion
}
}
測試程式碼如下:
複製程式碼程式碼如下:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using YanZhiwei.DotNet3._5.UtilitiesTests.Model;
namespace YanZhiwei.DotNet3._5.Utilities.Common.Tests
{
[TestClass()]
public class ScriptSerializerHelperTests
{
[TestMethod()]
public void SerializeTest()
{
Person _personA = new Person() { Name = "YanZhiweiA", Age = 10, Address = "shanghaiA" };
Person _personB = new Person() { Name = "YanZhiweiB", Age = 11, Address = "shanghaiB" };
IList<Person> _personList = new List<Person>();
_personList.Add(_personA);
_personList.Add(_personB);
string _actual = ScriptSerializerHelper.Serialize<Person>(_personList);
string _expect = "[{\"Name\":\"YanZhiweiA\",\"Age\":10,\"Address\":\"shanghaiA\"},{\"Name\":\"YanZhiweiB\",\"Age\":11,\"Address\":\"shanghaiB\"}]";
Assert.AreEqual<string>(_expect, _actual);
}
[TestMethod()]
public void DeserializeTest()
{
Person _personA = new Person() { Name = "YanZhiweiA", Age = 10, Address = "shanghaiA" };
Person _personB = new Person() { Name = "YanZhiweiB", Age = 11, Address = "shanghaiB" };
List<Person> _expected = new List<Person>();
_expected.Add(_personA);
_expected.Add(_personB);
string _jsonString = "[{'Name':'YanZhiweiA','Age':10,'Address':'shanghaiA'},{'Name':'YanZhiweiB','Age':11,'Address':'shanghaiB'}]";
List<Person> _result = (List<Person>)ScriptSerializerHelper.Deserialize<Person>(_jsonString);
bool _actual = _expected.SequenceEqual(_result, new PersonCompare());
Assert.IsTrue(_actual);
}
[TestMethod()]
public void ParseJsonTimeTest()
{
string _actual = ScriptSerializerHelper.ParseJsonTime(@"[{'getTime':'\/Date(1419564257428)\/'}]", "yyyyMMdd hh:mm:ss");
Assert.AreEqual("[{'getTime':'20141226 11:24:17'}]", _actual);
}
}
public class PersonCompare : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return (x.Age == y.Age) && (x.Address == y.Address) && (x.Name == y.Name);
}
public int GetHashCode(Person obj)
{
return obj.Name.GetHashCode();
}
}
}
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using YanZhiwei.DotNet3._5.UtilitiesTests.Model;
namespace YanZhiwei.DotNet3._5.Utilities.Common.Tests
{
[TestClass()]
public class ScriptSerializerHelperTests
{
[TestMethod()]
public void SerializeTest()
{
Person _personA = new Person() { Name = "YanZhiweiA", Age = 10, Address = "shanghaiA" };
Person _personB = new Person() { Name = "YanZhiweiB", Age = 11, Address = "shanghaiB" };
IList<Person> _personList = new List<Person>();
_personList.Add(_personA);
_personList.Add(_personB);
string _actual = ScriptSerializerHelper.Serialize<Person>(_personList);
string _expect = "[{\"Name\":\"YanZhiweiA\",\"Age\":10,\"Address\":\"shanghaiA\"},{\"Name\":\"YanZhiweiB\",\"Age\":11,\"Address\":\"shanghaiB\"}]";
Assert.AreEqual<string>(_expect, _actual);
}
[TestMethod()]
public void DeserializeTest()
{
Person _personA = new Person() { Name = "YanZhiweiA", Age = 10, Address = "shanghaiA" };
Person _personB = new Person() { Name = "YanZhiweiB", Age = 11, Address = "shanghaiB" };
List<Person> _expected = new List<Person>();
_expected.Add(_personA);
_expected.Add(_personB);
string _jsonString = "[{'Name':'YanZhiweiA','Age':10,'Address':'shanghaiA'},{'Name':'YanZhiweiB','Age':11,'Address':'shanghaiB'}]";
List<Person> _result = (List<Person>)ScriptSerializerHelper.Deserialize<Person>(_jsonString);
bool _actual = _expected.SequenceEqual(_result, new PersonCompare());
Assert.IsTrue(_actual);
}
[TestMethod()]
public void ParseJsonTimeTest()
{
string _actual = ScriptSerializerHelper.ParseJsonTime(@"[{'getTime':'\/Date(1419564257428)\/'}]", "yyyyMMdd hh:mm:ss");
Assert.AreEqual("[{'getTime':'20141226 11:24:17'}]", _actual);
}
}
public class PersonCompare : IEqualityComparer<Person>
{
public bool Equals(Person x, Person y)
{
return (x.Age == y.Age) && (x.Address == y.Address) && (x.Name == y.Name);
}
public int GetHashCode(Person obj)
{
return obj.Name.GetHashCode();
}
}
}
測試結果如下圖所示:
希望本文所述對大家的C#程式設計有所幫助。
相關文章
- C# HTTP幫助類C#HTTP
- 字元操作普通幫助類字元
- 資料庫幫助類資料庫
- Pgsql幫助類 netcoreSQLNetCore
- Sandcastle入門:建立C#幫助文件ASTC#
- 自然分類演算法例項程式碼分享演算法
- (精華)2020年6月26日 C#類庫 樹結構幫助類C#
- C#寫一套最全的MySQL幫助類(包括增刪改查)C#MySql
- DataGrid 匯出到 Excel 的幫助類Excel
- C#中類的建立和例項化C#
- AIX 中grep 的用法幫助AI
- ASP.NET_頁面中彈出對話方塊幫助類ASP.NET
- 學用Solaris系統幫助(轉)
- C# RESTful API 訪問輔助類C#RESTAPI
- 應該讓機器人幫助人類,還是讓人類幫助機器人?機器人
- 封裝type方法例項封裝
- 幫助命令
- [java程式碼]業務邏輯查詢幫助類Java
- WPF WriteableBitmap透過GDI+繪製幫助類
- JS中陣列與物件的遍歷方法例項JS陣列物件
- 用shell幫助解決ORA問題
- javascript this 用法例項程式碼解析JavaScript
- Java的clone()用法例項解析Java
- 邊界值分析法例項
- javascript 靜態方法和例項方法例項JavaScript
- requests庫幫助
- MySQL幫助使用MySql
- 請求幫助!
- 請求幫助:
- SQL的幫助SQL
- jdk幫助文件JDK
- 用 Git 幫助寫作者更好地完成工作Git
- 給你的WP應用加上幫助文件
- 貝葉斯分類演算法例項 --根據姓名推測男女演算法
- 貝葉斯分類演算法例項 –根據姓名推測男女演算法
- CodeSmith自帶的幫助文件中FAQMIT
- OllyScript v0.92中文幫助文件
- Oracle工具使用(export,import,sqlldr中文幫助及例項)(轉)OracleExportImportSQL