这次给大家带来json操作日期格式,json操作日期格式的注意事项有哪些,下面就是实战案例,一起来看一下。
开发中有时候需要从服务器端返回json格式的数据,在后台代码中如果有datetime类型的数据使用系统自带的工具类序列化后将得到一个很长的数字表示日期数据,如下所示:
//设置服务器响应的结果为纯文本格式
context.response.contenttype = text/plain;
//学生对象集合
list<student> students = new list<student>
{
new student(){name =tom,
birthday =convert.todatetime(2014-01-31 12:12:12)},
new student(){name =rose,
birthday =convert.todatetime(2014-01-10 11:12:12)},
new student(){name =mark,
birthday =convert.todatetime(2014-01-09 10:12:12)}
};
//javascript序列化器
javascriptserializer jss=new javascriptserializer();
//序列化学生集合对象得到json字符
string studentsjson=jss.serialize(students);
//将字符串响应到客户端
context.response.write(studentsjson);
context.response.end();
运行结果是:
其中tom所对应生日“2014-01-31”变成了1391141532000,这其实是1970 年 1 月 1 日至今的毫秒数;1391141532000/1000/60/60/24/365=44.11年,44+1970=2014年,按这种方法可以得出年月日时分秒和毫秒。这种格式是一种可行的表示形式但不是普通人可以看懂的友好格式,怎么让这个格式变化?
解决办法:
方法1:在服务器端将日期格式使用select方法或linq表达式转换后发到客户端:
using system;
using system.collections.generic;
using system.web;
using system.web.script.serialization;
namespace jsondate1
{
using system.linq;
/// <summary>
/// 学生类,测试用
/// </summary>
public class student
{
/// <summary>
/// 姓名
/// </summary>
public string name { get; set; }
/// <summary>
/// 生日
/// </summary>
public datetime birthday { get; set; }
}
/// <summary>
/// 返回学生集合的json字符
/// </summary>
public class getjson : ihttphandler
{
public void processrequest(httpcontext context)
{
//设置服务器响应的结果为纯文本格式
context.response.contenttype = text/plain;
//学生对象集合
list<student> students = new list<student>
{
new student(){name =tom,birthday =convert.todatetime(2014-01-31 12:12:12)},
new student(){name =rose,birthday =convert.todatetime(2014-01-10 11:12:12)},
new student(){name =mark,birthday =convert.todatetime(2014-01-09 10:12:12)}
};
//使用select方法重新投影对象集合将birthday属性转换成一个新的属性
//注意属性变化后要重新命名,并立即执行
var studentset =
students.select
(
p => new { p.name, birthday = p.birthday.tostring(yyyy-mm-dd) }
).tolist();
//javascript序列化器
javascriptserializer jss = new javascriptserializer();
//序列化学生集合对象得到json字符
string studentsjson = jss.serialize(studentset);
//将字符串响应到客户端
context.response.write(studentsjson);
context.response.end();
}
public bool isreusable
{
get
{
return false;
}
}
}
}
select方法重新投影对象集合将birthday属性转换成一个新的属性,注意属性变化后要重新命名,属性名可以相同;这里可以使用select方法也可以使用linq查询表达式,也可以选择别的方式达到相同的目的;这种办法可以将集合中客户端不用的属性剔除,达到简单优化性能的目的。
运行结果:
这时候的日期格式就已经变成友好格式了,不过在javascript中这只是一个字符串。
方法二:
在javascript中将birthday:\/date(1391141532000)\/中的字符串转换成javascript中的日期对象,可以将birthday这个key所对应的value中的非数字字符以替换的方式删除,到到一个数字1391141532000,然后实例化一个date对象,将1391141532000毫秒作为参数,得到一个javascript中的日期对象,代码如下:
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>json日期格式处理</title>
<script src="scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$.getjson(getjson.ashx, function (students) {
$.each(students, function (index, obj) {
$(<li/>).html(obj.name).appendto(#ulstudents);
//使用正则表达式将生日属性中的非数字(\d)删除
//并把得到的毫秒数转换成数字类型
var birthdaymilliseconds = parseint(obj.birthday.replace(/\d/igm, ));
//实例化一个新的日期格式,使用1970 年 1 月 1 日至今的毫秒数为参数
var birthday = new date(birthdaymilliseconds);
$(<li/>).html(birthday.tolocalestring()).appendto(#ulstudents); ;
});
});
});
</script>
</head>
<body>
<h2>json日期格式处理</h2>
<ul id="ulstudents">
</ul>
</body>
</html>
运行结果:
上的使用正则/\d/igm达到替换所有非数字的目的,\d表示非数字,igm是参数,分别表示忽视(ignore)大小写;多次、全局(global)替换;多行替换(multi-line);有一些时候还会出现+86的情况,只需要变换正则同样可以达到目的。另外如果项目中反复出现这种需要处理日期格式的问题,可以扩展一个javascript方法,代码如下:
$(function () {
$.getjson(getjson.ashx, function (students) {
$.each(students, function (index, obj) {
$(<li/>).html(obj.name).appendto(#ulstudents);
//使用正则表达式将生日属性中的非数字(\d)删除
//并把得到的毫秒数转换成数字类型
var birthdaymilliseconds = parseint(obj.birthday.replace(/\d/igm, ));
//实例化一个新的日期格式,使用1970 年 1 月 1 日至今的毫秒数为参数
var birthday = new date(birthdaymilliseconds);
$(<li/>).html(birthday.tolocalestring()).appendto(#ulstudents);
$(<li/>).html(obj.birthday.todate()).appendto(#ulstudents);
});
});
});
//在string对象中扩展一个todate方法,可以根据要求完善
string.prototype.todate = function () {
var datemilliseconds;
if (isnan(this)) {
//使用正则表达式将日期属性中的非数字(\d)删除
datemilliseconds =this.replace(/\d/igm, );
} else {
datemilliseconds=this;
}
//实例化一个新的日期格式,使用1970 年 1 月 1 日至今的毫秒数为参数
return new date(parseint(datemilliseconds));
};
上面扩展的方法todate不一定合理,也不够强大,可以根据需要修改。
方法三:
可以选择一些第三方的json工具类,其中不乏有一些已经对日期格式问题已处理好了的,常见的json序列化与反序列化工具库有:
1.fastjson.
2.json_checker.
3.jayrock.
4.json.net - linq to json.
5.litjson.
6.json for .net.
7.jsonfx.
8.jsonsharp.
9.jsonexserializer.
10.fluent-json
11.manatee json
这里以litjson为序列化与反序列化json的工具类作示例,代码如下:
using system;
using system.collections.generic;
using system.web;
using litjson;
namespace jsondate2
{
using system.linq;
/// <summary>
/// 学生类,测试用
/// </summary>
public class student
{
/// <summary>
/// 姓名
/// </summary>
public string name { get; set; }
/// <summary>
/// 生日
/// </summary>
public datetime birthday { get; set; }
}
/// <summary>
/// 返回学生集合的json字符
/// </summary>
public class getjson : ihttphandler
{
public void processrequest(httpcontext context)
{
//设置服务器响应的结果为纯文本格式
context.response.contenttype = text/plain;
//学生对象集合
list<student> students = new list<student>
{
new student(){name =tom,birthday =convert.todatetime(2014-01-31 12:12:12)},
new student(){name =rose,birthday =convert.todatetime(2014-01-10 11:12:12)},
new student(){name =mark,birthday =convert.todatetime(2014-01-09 10:12:12)}
};
//序列化学生集合对象得到json字符
string studentsjson = jsonmapper.tojson(students);
//将字符串响应到客户端
context.response.write(studentsjson);
context.response.end();
}
public bool isreusable
{
get
{
return false;
}
}
}
}
运行结果如下:
这时候的日期格式就基本正确了,只要在javascript中直接实例化日期就好了,
var date = new date(01/31/2014 12:12:12);
alert(date.tolocalestring());
客户端的代码如下:
$(function () {
$.getjson(getjson2.ashx, function (students) {
$.each(students, function (index, obj) {
$(<li/>).html(obj.name).appendto(#ulstudents);
var birthday = new date(obj.birthday);
$(<li/>).html(birthday.tolocalestring()).appendto(#ulstudents);
});
});
});
var date = new date(01/31/2014 12:12:12);
alert(date.tolocalestring());
方法四:
这点文字发到博客上有网友提出了他们宝贵的意见,我并没有考虑在mvc中的情况,其实mvc中也可以使用handler,所以区别不是很大了,但mvc中有专门针对服务器响应为json的action,代码如下:
using system;
using system.web.mvc;
namespace jsondatemvc.controllers
{
public class homecontroller : controller
{
public jsonresult getjson1()
{
//序列化当前日期与时间对象,并允许客户端get请求
return json(datetime.now, jsonrequestbehavior.allowget);
}
}
}
运行结果:
下载一个内容为application/json的文件,文件名为getjson1,内容是\/date(1391418272884)\/
从上面的情况看来mvc中序列化时并未对日期格式特别处理,我们可以反编译看源码:
return调用的json方法:
protected internal jsonresult json(object data, jsonrequestbehavior behavior)
{
return this.json(data, null, null, behavior);
}
this.json方法
protected internal virtual jsonresult json(object data, string contenttype, encoding contentencoding, jsonrequestbehavior behavior)
{
return new jsonresult { data = data, contenttype = contenttype, contentencoding = contentencoding, jsonrequestbehavior = behavior };
}
jsonresult类actionresult类的子类,executeresult方法:
从上面的代码中不难看出微软的jsonresult类仍然是使用了javascriptserializer,所以返回的结果与方法一未处理时是一样的,要解决这个问题我们可以派生出一个新的类,重写executeresult方法,使用json.net来完成序列化工作,jsonresultpro.cs文件的代码如下:
namespace jsondatemvc.common
{
using system;
using system.web;
using system.web.mvc;
using newtonsoft.json;
using newtonsoft.json.converters;
public class jsonresultpro : jsonresult
{
public jsonresultpro(){}
public jsonresultpro(object data, jsonrequestbehavior behavior)
{
base.data = data;
base.jsonrequestbehavior = behavior;
this.datetimeformat = yyyy-mm-dd hh:mm:ss;
}
public jsonresultpro(object data, string datetimeformat)
{
base.data = data;
base.jsonrequestbehavior = jsonrequestbehavior.allowget;
this.datetimeformat = datetimeformat;
}
/// <summary>
/// 日期格式
/// </summary>
public string datetimeformat{ get; set; }
public override void executeresult(controllercontext context)
{
if (context == null)
{
throw new argumentnullexception(context);
}
if ((this.jsonrequestbehavior == jsonrequestbehavior.denyget) && string.equals(context.httpcontext.request.httpmethod, get, stringcomparison.ordinalignorecase))
{
throw new invalidoperationexception(mvcresources.jsonrequest_getnotallowed);
}
httpresponsebase base2 = context.httpcontext.response;
if (!string.isnullorempty(this.contenttype))
{
base2.contenttype = this.contenttype;
}
else
{
base2.contenttype = application/json;
}
if (this.contentencoding != null)
{
base2.contentencoding = this.contentencoding;
}
if (this.data != null)
{
//转换system.datetime的日期格式到 iso 8601日期格式
//iso 8601 (如2008-04-12t12:53z)
isodatetimeconverter isodatetimeconverter=new isodatetimeconverter();
//设置日期格式
isodatetimeconverter.datetimeformat = datetimeformat;
//序列化
string jsonresult = jsonconvert.serializeobject(this.data,isodatetimeconverter);
//相应结果
base2.write(jsonresult);
}
}
}
}
使用上面的jsonresultpro action类型的代码如下:
public jsonresultpro getjson2()
{
//序列化当前日期与时间对象,并允许客户端get请求,注意h是大写
return new jsonresultpro(datetime.now,yyyy-mm-dd hh:mm);
}
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
jsonp+json实现ajax跨域请求
jsonp怎样才能解决ajax跨域
以上就是json操作日期格式的详细内容。