package wms.common; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.serializer.SerializeConfig; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; import wms.entity.ResultBean; import java.util.Date; import java.util.List; /** * * DESC: 封裝一個結果類型的字符串,包括success和msg兩個字段 */ public class JsonFormat {
//格式化日期 private static String dateFormat; static { dateFormat = "yyyy-MM-dd HH:mm:ss"; } private static SerializeConfig mapping = new SerializeConfig(); static { //jackson默認寫出的時間數據為時間戳, 這里修改為相應模式的時間數據輸出格式 mapping.put(Date.class, new SimpleDateFormatSerializer(dateFormat)); } /** * 將對象或集合轉換為json字符串 * @param obj * @return */ public final static String toString(Object obj){ return JSONObject.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue); } /** * 將對象或集合轉換為json字符串 * @param obj * @return */ public final static String toStringWithoutNull(Object obj){ return JSONObject.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss"); } /** * 將結果字符串轉換為標准結果集 * @param success * @param msg * @return {"success":success,"msg":msg} */ public final static String toStringResult(boolean success, String msg){ return String.format("{\"success\":%s,\"msg\":\"%s\"}", success?"true":"false", msg); } public final static String toStatusResult(int status, Object data){ return String.format("{\"status\":%s,\"data\":%s}", status, toString(data)); } public final static String toStatusResult(ResultBean data){ if (data.getData() instanceof String) return data.toString(); else return toStatusResult(data.getStatus(), data.getData()); } /** * 將對象轉換為標准結果集 * @param success * @param msg * @return {"success":success,"msg":msg} */ public final static String toObjectResult(boolean success, Object msg){ if (msg != null) return String.format("{\"success\":%s,\"msg\":%s}", success, JSONObject.toJSONStringWithDateFormat(msg, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue)); else //把null集合轉換為[],是為了kendo ui dataSource,直接返回null,會出現Status code=200的異常 return String.format("{\"success\":%s,\"msg\":\"[]\"}", success); } public final static String toString(String key, Object msg){ return String.format("{\"%s\":%s}", key, JSONObject.toJSONStringWithDateFormat(msg, "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue)); } public final static String toPageString(Integer total, List data){ if (total == null || total == 0) return emptyPageString(); return String.format("{\"total\":%s, \"data\":%s}", total, JSONObject.toJSONStringWithDateFormat(data, "yyyy-MM-dd HH:mm:ss")); } public final static String toPageString(List data){ if (data.size() == 0) return emptyPageString(); return String.format("{\"total\":%s, \"data\":%s}", data.size(), JSONObject.toJSONStringWithDateFormat(data, "yyyy-MM-dd HH:mm:ss")); } public final static String emptyPageString(){ return "{\"total\":0, \"data\":\"\"}"; } }
