1. Json-lib能夠將Java對象很方便的轉成json格式的字符串java
可是java裏面時間類型轉換成json數據就成這樣啦
"createTime":{"date":30,"day":3,"hours":15,"minutes":14,"month":3,"nanos":0,"seconds"
:38,"time":1209539678000,"timezoneOffset":-480,"year":108}sql
2.解決方式以下json
List<Dept> deptList = deptService.selectBypage(map);運維
int count = deptService.selectDept();ui
JSONArray ja = new JSONArray();this
JsonConfig jf = new JsonConfig();spa
這種是時間戳Timestampcode
jf.registerJsonValueProcessor(java.sql.Timestamp.class, new DateJsonValueProcessor("yyyy-MM-dd"));orm
還有一種是Date對象
jf.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
JSONObject jsonObject = new JSONObject();
jsonObject.put("count", count);
jsonObject.put("code", 0);
jsonObject.put("msg", "null");
jsonObject.put("data", ja.fromObject(deptList, jf));
注意:以上這種返回格式是使用layui所返回的json參數類型
DateJsonValueProcessor是實現了一個JsonValueProcessor接口
新建DateJsonValueProcessor實現json-lib中的sonValueProcessor接口
package com.siyuan.service.Impl;
import java.text.SimpleDateFormat;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;
public class DateJsonValueProcessor implements JsonValueProcessor {
private String format;
public DateJsonValueProcessor(String format){
this.format = format;
}
public Object processArrayValue(Object value, JsonConfig jsonConfig)
{
return null;
}
public Object processObjectValue(String key, Object value, JsonConfig jsonConfig)
{
if(value == null)
{
return "";
}
if(value instanceof java.sql.Timestamp)
{
String str = new SimpleDateFormat(format).format((java.sql.Timestamp)value);
return str;
}
if (value instanceof java.util.Date)
{
String str = new SimpleDateFormat(format).format((java.util.Date) value);
return str;
}
return value.toString();
}
}
以上代碼是時間類型被處理格式化
這樣就解決了以上問題,運行結果爲
{"count":11,"code":0,"msg":null,"data":[{"deleteflg":0,"deptid":1,"deptname":"人事部","inserttime":"2018-02-02","updatetime":"2018-02-02"},{"deleteflg":0,"deptid":2,"deptname":"採購部","inserttime":"2018-02-02","updatetime":"2018-02-02"},{"deleteflg":0,"deptid":3,"deptname":"技術部","inserttime":"2018-02-03","updatetime":"2018-02-03"},{"deleteflg":0,"deptid":4,"deptname":"調研部","inserttime":"2018-02-03","updatetime":"2018-02-03"},{"deleteflg":0,"deptid":5,"deptname":"運維部","inserttime":"2018-02-03","updatetime":"2018-02-03"},{"deleteflg":0,"deptid":6,"deptname":"總裁部","inserttime":"2018-02-03","updatetime":"2018-02-03"},{"deleteflg":0,"deptid":7,"deptname":"祕書部","inserttime":"2018-02-03","updatetime":"2018-02-03"},{"deleteflg":0,"deptid":8,"deptname":"經理部","inserttime":"2018-02-03","updatetime":"2018-02-03"},{"deleteflg":0,"deptid":9,"deptname":"財務部","inserttime":"2018-02-03","updatetime":"2018-02-03"},{"deleteflg":0,"deptid":10,"deptname":"科研部","inserttime":"2018-02-03","updatetime":"2018-02-03"}]}
但願可以幫助到你們