C#中JavaScriptSerializer帮助类用法实例
程序员文章站
2024-02-11 14:10:16
本文实例讲述了c#中javascriptserializer帮助类用法。分享给大家供大家参考。具体如下:
关键代码如下:
复制代码 代码如下:using system;...
本文实例讲述了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#程序设计有所帮助。