/** * 除去不想生成的字段(特别适合去掉级联的对象)+时间转换 * * @param excludes 除去不想生成的字�? * @param datePattern * @return */ public static JsonConfig configJson(String[] excludes, String datePattern) { JsonConfig jsonConfig = new JsonConfig(); jsonConfig.setExcludes(excludes); jsonConfig.setIgnoreDefaultExcludes(true); jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); jsonConfig.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor(datePattern)); return jsonConfig; }
/** * 将对象等转换为json格式并输出 @Title outJson * * @author hedj @Description: * @date 2013-12-6 * @param obj 要转换的对象 * @param objs 可变参数 第一个参数日期格式,默认为"yyyy-MM-dd" * @return */ public static String toJsonString(Object obj, Object... objs) { try { String dateFormat = DateUtil.DATE_FORMAT; if (objs != null && objs.length > 0) { dateFormat = (String) objs[0]; } JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor(dateFormat)); config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); return JSONObject.fromObject(obj, config).toString(); } catch (Exception e) { log.error(" 转换JSON错误:", e); return ""; } }
/** * 将对象等转换为json格式并输出 @Title outJson * * @author hedj @Description: * @date 2013-12-6 * @param obj 要转换的对象 * @param objs 可变参数 第一个参数日期格式,默认为"yyyy-MM-dd" * @return */ public static String outJson(Object obj, Object... objs) { try { String dateFormat = DateUtil.DATE_FORMAT; if (objs != null && objs.length > 0) { dateFormat = (String) objs[0]; } JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor(dateFormat)); config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); String json = JSONObject.fromObject(obj, config).toString(); getResponse().setContentType("text/html;charset=UTF-8"); PrintWriter out = getResponse().getWriter(); out.write(json); return json; } catch (Exception e) { log.error(" 转换JSON错误:", e); return ""; } }
private static void setConfig(JsonConfig jsonConfig, String[] excludes) { jsonConfig.setExcludes(excludes); jsonConfig.setIgnoreDefaultExcludes(false); jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); }