1.JSON日期格式轉換
默認JSON對DATE類型會轉換成一個多屬性對象, 而不是單獨的一個字符串, 在某些應用處理上不是很方便, 可以利用JsonValueProcessor來實現日期的轉換.
默認格式:
"lastUpdate": {
"date": 29,
"day": 3,
"hours": 14,
"minutes": 46,
"month": 1,
"seconds": 41,
"time": 1330498001000,
"timezoneOffset": -480,
"year": 112
},
轉換後格式:
"lastUpdate": "2012-02-29 14:46:41"
自定義一個日期處理器:
- import java.text.SimpleDateFormat;
- import java.util.Date;
-
- import net.sf.json.JsonConfig;
- import net.sf.json.processors.JsonValueProcessor;
-
- /**
- * JSON日期格式轉換
- *
- */
- public class DateJsonValueProcessor implements JsonValueProcessor
- {
- private String format = "yyyy-MM-dd HH:mm:ss";
-
- public DateJsonValueProcessor()
- {
-
- }
-
- public DateJsonValueProcessor(String format)
- {
-
- this.format = format;
- }
-
- public Object processArrayValue(Object value, JsonConfig jsonConfig)
- {
-
- String[] obj = {};
- if (value instanceof Date[])
- {
- SimpleDateFormat sf = new SimpleDateFormat(format);
- Date[] dates = (Date[]) value;
- obj = new String[dates.length];
- for (int i = 0; i < dates.length; i++)
- {
- obj[i] = sf.format(dates[i]);
- }
- }
- return obj;
- }
-
- public Object processObjectValue(String key, Object value, JsonConfig jsonConfig)
- {
-
- if (value instanceof Date)
- {
- String str = new SimpleDateFormat(format).format((Date) value);
- return str;
- }
- return value;
- }
-
- public String getFormat()
- {
-
- return format;
- }
-
- public void setFormat(String format)
- {
-
- this.format = format;
- }
-
- }
轉換調用代碼:
- JsonConfig jsonConfig = new JsonConfig();
- jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor());
- JSONObject jsonObj = JSONObject.fromObject(bean, jsonConfig);
- return jsonObj.toString();