JSON拼接
传入对象o、JSON json、JSON key 、属性名valeKey
/**
* putJson
*
* @param success 是否成功
* @param o 对象
* @param json 拼接的json
* @param key jsonkey
* @param valeKey 对象方法名
*/
private void putJson(Boolean success, Object o,
JSONObject json, String key, String valeKey) {
Class<? extends Object> classSourceType = o.getClass();
String getMethodName = "get" + valeKey;
try {
Method getMethod = classSourceType
.getMethod(getMethodName, new Class[] {});
Object value = getMethod.invoke(o, new Object[] {});
if (value == null) {
logger.info("空节点:" + valeKey + "表名:"
+ classSourceType.getName());
json.put(key, StringUtils.EMPTY);
} else {
Class<?> returnType = getMethod.getReturnType();
if (returnType.isAssignableFrom(Date.class)) {
json.put(key, dateFormat(value, "yyyy-MM-dd"));
} else if (returnType.isAssignableFrom(Double.class)) {
json.put(key, changeToString((Double) value));
} else {
json.put(key, value);
}
}
} catch (Exception e) {
logger.error("节点构建失败,节点名称:" + key + ",失败原因:反射拿值出错,表名:"
+ classSourceType.getName());
success = false;
}
}
/**
* 日期取到月
*
* @param date
* @param pattern 格式
* @return
*/
private String dateFormat(Object date, String pattern) {
if (null == date) {
return "";
}
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
if (!(date instanceof Date)) {
date = DateUtils.parseDateTime(date.toString(), pattern);
}
return formatter.format(date);
}
/**
* 科学记数法问题
* @param number
* @return
*/
private String changeToString(Double number) {
if (number != null) {
BigDecimal bigDecimal = BigDecimal.valueOf(number);
if (StringUtils.contains(bigDecimal.toString(), "E")) {
BigDecimal bigDecimal3 = new BigDecimal(number);
return bigDecimal3.toPlainString();
} else {
return bigDecimal.toString();
}
} else {
return "";
}
}
工具类获取属性值:
commons-beanutils\1.8.0\commons-beanutils-1.8.0.jar
public static Object getProperty(Object bean, String name)
throws IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
return (PropertyUtilsBean.getInstance().getProperty(bean, name));
}