package com.cjonline.foundation.util;
import java.lang.reflect.Array; import java.util.Date;
import net.sf.json.JSONArray; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.util.PropertyFilter; @SuppressWarnings("all") public class JsonToJavaUtil { /** * 将json转成成javaBean对象 * @param <T> 返回类型 * @param json 字符串 * @param clazz 需要转换成的类 * @return */ public static <T> T[] jsonToJavaBean(String json,Class<T> clazz) { if(json==null || !json.startsWith("[") || !json.endsWith("]") ){ throw new RuntimeException("JSONArray 必须以'['开头,以']'结尾"); } JSONArray array = JSONArray.fromObject(json); //先读取字符串数组 Object[] objs = array.toArray(); //转成对像数组 if(objs.length>0){ JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor()); T[] tArrs = (T[]) Array.newInstance(clazz,objs.length); for(int i=0;i<objs.length;i++){ JSONObject jsonObj = JSONObject.fromObject(objs[i],config); //再使用JsonObject遍历一个个的对像 T t = (T) jsonObj.toBean(jsonObj,clazz); //指定转换的类型,但仍需要强制转化-成功 tArrs[i]=t; } return tArrs; } return null; } /** * 将javaBean转成json串 * @param obj 对象 * @param ignore 过滤掉的属性 * @return */ public static String javaBeanToJson(Object obj,final String[] ignore){ JsonConfig config = new JsonConfig(); config.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor()); PropertyFilter filter = new PropertyFilter(){ public boolean apply(Object source,String name,Object value){ if(ignore!=null && ignore.length>0){ for(String s : ignore){ if(s!=null && s.equals(name)) { return true; } } } return false; } }; config.setJsonPropertyFilter(filter); JSONArray s = JSONArray.fromObject(obj,config); return s.toString(); } }
package com.cjonline.foundation.util;
import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale;
import net.sf.json.JsonConfig; import net.sf.json.processors.JsonValueProcessor;
public class JsonDateValueProcessor implements JsonValueProcessor { /** * datePattern */ private String datePattern = "yyyy-MM-dd"; /** * JsonDateValueProcessor */ public JsonDateValueProcessor() { super(); } public JsonDateValueProcessor(String format) { super(); this.datePattern = format; } public Object processArrayValue(Object value,JsonConfig jsonConfig) { return process(value); } public Object processObjectValue(String key,Object value,JsonConfig jsonConfig) { return process(value); } private Object process(Object value) { try { if (value instanceof Date) { SimpleDateFormat sdf = new SimpleDateFormat(datePattern,Locale.UK); return sdf.format((Date) value); } return value == null ? "" : value.toString(); } catch (Exception e) { return ""; } } public String getDatePattern() { return datePattern; } public void setDatePattern(String pDatePattern){ datePattern = pDatePattern; } } (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|