JAVA中的JSON辅助类
/** * 将bean的一组属性,输出成json结果 * * @param bean * @param exclude true为将参数中的属性排除在外,false为将参数中的属性输出成json * @param fieldNames * @return */ public static Map<String, Object> getFieldValues(Object bean, boolean exclude, String... fieldNames) { if (bean == null) return Collections.emptyMap(); BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean); Set<String> fields; if (ArrayUtils.isEmpty(fieldNames)) { fields = new HashSet<String>(); } else { fields = new HashSet<String>(Arrays.asList(fieldNames)); } Map<String, Object> ret = new LinkedHashMap<String, Object>(); PropertyDescriptor[] descriptors = beanWrapper.getPropertyDescriptors(); for (PropertyDescriptor pd : descriptors) { if (pd.getReadMethod() == null) continue; String name = pd.getName(); if (exclude) { if (fields.contains(name)) continue; } else { if (!fields.contains(name)) continue; } ret.put(name, beanWrapper.getPropertyValue(name)); } return ret; }
//=================================把json字符串转成java类型; /** * 把json字符串转换成为java对象; * 字符串是符合json规则的; * {"...":"...","...":"..."} */ public static Object fromStrToObject(String str,Class clazz,Map classMap){ JSONObject json = JSONObject.fromObject(str); Object bean = null; if(clazz == null){ bean = JSONObject.toBean(json); }else if(clazz != null){ if(classMap != null){ bean = JSONObject.toBean(json,clazz,classMap); }else{ bean = JSONObject.toBean(json,clazz); } } return bean; } public static List fromStrToList(String str, Class clazz, Map classMap) { JSONArray array = JSONArray.fromObject(str); List list = new ArrayList(); for (int i = 0; i < array.size(); i++) { JSONObject obj = array.getJSONObject(i); Object bean = null; if (clazz == null) { bean = JSONObject.toBean(obj); } else if (clazz != null) { if (classMap != null) { bean = JSONObject.toBean(obj, clazz, classMap); } else { bean = JSONObject.toBean(obj, clazz); } } list.add(bean); } return list; }