JSON日期格式转换
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();
?
2. 利用JAVA反射机制将JSON数据转换成JAVA对象
net.sf.json.JSONObject为我们提供了toBean方法用来转换为JAVA对象,?功能更为强大, ?这里借鉴采用JDK的反射机制,?作为简单的辅助工具使用,?? 有些数据类型需要进行转换, 根据需要进行扩展,? 这里可以处理Long和Date类型.
只支持单个JSONObject对象的处理,?? 对于复杂的JSON对象, 如JSONArray数组,?可考虑先遍历, 获取JSONObject后再进行处理.?
?
import java.lang.reflect.Method;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.List;import org.json.JSONObject;/** * 辅助处理工具 * */public class AssistantUtil{private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");/** * 把JSON数据转换成JAVA对象 * description: 函数的目的/功能 */public static void setJsonObjData(Object obj, JSONObject data, String[] excludes) throws Exception{// 反射获取所有方法Method[] methods = obj.getClass().getDeclaredMethods();if (null != methods){for (Method m : methods){String methodName = m.getName();if (methodName.startsWith("set")){methodName = methodName.substring(3);// 获取属性名称methodName = methodName.substring(0, 1).toLowerCase() + methodName.substring(1);if (!methodName.equalsIgnoreCase("class") && !isExistProp(excludes, methodName)){try{m.invoke(obj, new Object[] { data.get(methodName) });}catch (IllegalArgumentException e1){if(m.getParameterTypes()[0].getName().equals("java.lang.Long")){m.invoke(obj, new Object[] { Long.valueOf(data.get(methodName).toString())});}else if(m.getParameterTypes()[0].getName().equals("java.util.Date")){m.invoke(obj, new Object[] {!data.isNull(methodName)? sdf.parse(data.get(methodName).toString()) : null});}}catch (Exception e){}}}}}}private static boolean isExistProp(String[] excludes, String prop){if (null != excludes){for (String exclude : excludes){if (prop.equals(exclude)){return true;}}}return false;}}
?