[C #] JavaScriptSerializer help class,
Key code:
Using System; using System. collections. generic; using System. text. regularExpressions; using System. web. script. serialization; namespace YanZhiwei. dotNet3. _ 5. utilities. common {// <summary> /// JavaScriptSerializer help class /// </summary> public static class ScriptSerializerHelper {# region processing time format of Json strings // <summary> /// processing the time format of JsonString // <para> eg: scriptSerializerHelper. parseJsonTime (@ "[{'gettime': '\/Date (1419564257428) \/'}]", "yyyyMMdd hh: mm: ss "); ==> [{'gettime': '2014 11:24:17 '}] </para> // <para> reference: http://www.cnphp6.com/archives/35773 </Para> /// </summary> /// <param name = "jsonString"> Json string </param> /// <param name = "formart"> time formatting type </param> /// <returns> processed Json string </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 >/// handle the time format of JsonString. [Time Format: yyyy-MM-dd HH: mm: ss /// <para> reference: http://www.cnphp6.com/archives/35773 </Para> /// </summary> /// <param name = "jsonString"> Json string </param> /// <returns> the processed Json string </param>/ returns> public static string ParseJsonTime (this string jsonString) {return ParseJsonTime (jsonString, "yyyy-MM-dd HH: mm: ss ");} # endregion # region serialize an object to JSON using JavaScriptSerializer // <summary> // use JavaScriptSerializer to serialize the object to a JSON string // <para> eg: ScriptSerializerHelper. serialize <Person> (_ personList); </p Ara> /// </summary> /// <typeparam name = "T"> generic </typeparam> /// <param name = "entityList"> object set </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 deserialization of json strings using JavaScriptSerializer // <summary> // deserialization of json strings using JavaScriptSerializer // <para> eg: list <Person> _ result = (List <Person>) ScriptSerializerHelper. deserialize <Pers On> (_ jsonString ); </para> /// </summary> /// <typeparam name = "T"> generic </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 }}
Code test:
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(); } }}
Test results:
Hope this is helpful! Thank you.