- 浏览: 43363 次
- 性别:
- 来自: 杭州
文章分类
最新评论
-
hecongqi:
这个确实很有用,要是开源就好了
Excel 数据校验项目的设计分享 -
zzc545732519:
大侠,可否给我传一份你的源代码呢,很想学习学习!!!
Excel 数据校验项目的设计分享 -
yhman:
阿里巴巴的
Excel 数据校验项目的设计分享 -
yuechengkun:
楼主,你的这个EXCEL解析我比较感兴趣,之前我也是通过在配置 ...
Excel 数据校验项目的设计分享
import java.beans.PropertyDescriptor; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.math.BigDecimal; import java.math.BigInteger; import java.net.URLDecoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import ognl.OgnlOps; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONArray; import org.json.JSONObject; import com.opensymphony.xwork.util.OgnlUtil; /** * java对象与json字符串互转的工具类 * */ public class JsonUtil { /** * 将json字符串转成javabean * @param jsonStr 要转换的json字符串 * @param toClass 要转化到的类型 * @param childMap 该类型中集合字段的字段名和集合元素类型map * @return Object * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */ @SuppressWarnings("unchecked") public static Object json2Bean(Class toClass,String jsonValue,Map<String,Class> childMap) throws Exception{ if( toClass == null || StringUtils.isBlank(jsonValue)) { return null; } try{ jsonValue = URLDecoder.decode(jsonValue, "utf-8"); }catch(Exception e){ throw new Exception("编码格式错误!"); } JSONObject object = null; try{ object= new JSONObject(jsonValue); }catch(Exception e){ throw new Exception("json格式错误!"); } Object obj = toClass.newInstance(); Map<String,Object> sourceMap = toMap(object); PropertyDescriptor[] props = OgnlUtil.getPropertyDescriptors(obj); Map<String,Object> map = new HashMap<String,Object>(); //参数不区分大小写 for (PropertyDescriptor desc : props) { Set entrys = sourceMap.entrySet(); boolean contains = false; for(Iterator i = entrys.iterator();i.hasNext();){ Entry entry = (Entry) i.next(); if(((String)entry.getKey()).equalsIgnoreCase(desc.getName())){ map.put(desc.getName(), entry.getValue()); contains = true; break; } } if( contains ) { Object value = null; // 处理日期型 // "yyyy-MM-dd'T'HH:mm:ss'Z'"此格式是由json2.js转换后的Date格式 if(java.util.Date.class.isAssignableFrom(desc.getPropertyType())) { String date = (String) map.get(desc.getName()); if(!validateDate(date)){ throw new Exception(desc.getName()+"日期格式错误!"); } value = new SimpleDateFormat("yyyy-MM-dd").parse(date.trim()); } else if(java.sql.Date.class.isAssignableFrom(desc.getPropertyType())) { String date = (String) map.get(desc.getName()); if(!validateDate(date)){ throw new Exception(desc.getName()+"日期格式错误!"); } value = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse( date.trim()).getTime()); } else if(Collection.class.isAssignableFrom(desc.getPropertyType())) { Class clz = childMap.get(desc.getName()); if(clz.isPrimitive() || CharSequence.class.isAssignableFrom(clz) || Number.class.isAssignableFrom(clz)) value = convertFromStringListSimple(map.get(desc.getName()).toString(),clz); else value = convertFromStringListComplex(map.get(desc.getName()).toString(),clz); } else { if(desc.getPropertyType().isPrimitive() || CharSequence.class.isAssignableFrom(desc.getPropertyType()) || Number.class.isAssignableFrom(desc.getPropertyType())){ try{ value = OgnlOps.convertValue(map.get(desc.getName()), desc.getPropertyType()); }catch(NumberFormatException e){ Class clz = desc.getPropertyType(); if(clz == Integer.TYPE||clz == Short.TYPE||clz == Long.TYPE||clz == BigInteger.class) throw new Exception(desc.getName()+"应为整数!"); else if(clz == Double.TYPE||clz == Float.TYPE||clz == BigDecimal.class) throw new Exception(desc.getName()+"应为数字!"); } } else { value = json2Bean(desc.getPropertyType(),map.get(desc.getName()).toString(),null); } } desc.getWriteMethod().invoke(obj, new Object[] { value }); } } return obj; } /** * 将json字符串转成javabean 日期格式默认为yyyy-MM-dd HH:mm:ss * @param jsonStr 要转换的json字符串 * @param toClass 要转化到的类型 * @param childMap 该类型中集合字段的字段名和集合元素类型map * @param DateStyle 日期时间格式 * @return Object * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws ParseException */ @SuppressWarnings("unchecked") public static Object json2Bean(Class toClass,String jsonValue,Map<String,Class> childMap,String DateStyle) throws Exception{ if(StringUtils.isBlank(DateStyle)){ DateStyle = DateUtil.DEFAULT_DATETIME_FORMAT; } if( toClass == null) { return null; } try{ jsonValue = URLDecoder.decode(jsonValue, "utf-8"); }catch(Exception e){ throw new Exception("编码格式错误!"); } JSONObject object = null; try{ object= new JSONObject(jsonValue); }catch(Exception e){ throw new Exception("json格式错误!"); } Object obj = toClass.newInstance(); Map<String,Object> sourceMap = toMap(object); PropertyDescriptor[] props = OgnlUtil.getPropertyDescriptors(obj); Map<String,Object> map = new HashMap<String,Object>(); //参数不区分大小写 for (PropertyDescriptor desc : props) { Set entrys = sourceMap.entrySet(); boolean contains = false; for(Iterator i = entrys.iterator();i.hasNext();){ Entry entry = (Entry) i.next(); if(((String)entry.getKey()).equalsIgnoreCase(desc.getName())){ map.put(desc.getName(), entry.getValue()); contains = true; break; } } if( contains ) { Object value = null; // 处理日期型 // "yyyy-MM-dd'T'HH:mm:ss'Z'"此格式是由json2.js转换后的Date格式 if(java.util.Date.class.isAssignableFrom(desc.getPropertyType())) { String date = (String) map.get(desc.getName()); try{ value = new SimpleDateFormat(DateStyle).parse(date.trim()); }catch(ParseException e3){ throw new Exception(desc.getName()+"="+date+";日期格式错误!"); } } else if(java.sql.Date.class.isAssignableFrom(desc.getPropertyType())) { String date = (String) map.get(desc.getName()); try{ value = new java.sql.Date(new SimpleDateFormat(DateStyle).parse( date.trim()).getTime()); }catch(ParseException e3){ throw new Exception(desc.getName()+"="+date+";日期格式错误!"); } } else if(Collection.class.isAssignableFrom(desc.getPropertyType())) { Class clz = childMap.get(desc.getName()); if(clz.isPrimitive() || CharSequence.class.isAssignableFrom(clz) || Number.class.isAssignableFrom(clz)) value = convertFromStringListSimple(map.get(desc.getName()).toString(),clz); else value = convertFromStringListComplex(map.get(desc.getName()).toString(),clz); } else { if(desc.getPropertyType().isPrimitive() || CharSequence.class.isAssignableFrom(desc.getPropertyType()) || Number.class.isAssignableFrom(desc.getPropertyType())){ try{ value = OgnlOps.convertValue(map.get(desc.getName()), desc.getPropertyType()); }catch(NumberFormatException e){ Class clz = desc.getPropertyType(); if(clz == Integer.TYPE||clz == Short.TYPE||clz == Long.TYPE||clz == BigInteger.class) throw new Exception(desc.getName()+"应为整数!"); else if(clz == Double.TYPE||clz == Float.TYPE||clz == BigDecimal.class) throw new Exception(desc.getName()+"应为数字!"); } } else { value = json2Bean(desc.getPropertyType(),map.get(desc.getName()).toString(),null); } } desc.getWriteMethod().invoke(obj, new Object[] { value }); } } return obj; } public static Map<String,Object> json2Map(String jsonValue) throws Exception{ if (StringUtils.isBlank(jsonValue)) { return null; } try { jsonValue = URLDecoder.decode(jsonValue, "utf-8"); } catch (Exception e) { throw new Exception("编码格式错误!"); } JSONObject object = null; try { object = new JSONObject(jsonValue); } catch (Exception e) { throw new Exception("json格式错误!"); } return toMap(object); } @SuppressWarnings("unchecked") public static List<Map<String,String>> json2List(String jsonValue) throws Exception{ if (StringUtils.isBlank(jsonValue)) { return null; } try { jsonValue = URLDecoder.decode(jsonValue, "utf-8"); } catch (Exception e) { throw new Exception("编码格式错误!"); } JSONArray array = new JSONArray(jsonValue); List<Map<String,String>> jsonList = new ArrayList<Map<String,String>>(); for(int i=0;i<array.length();i++){ Map jsonMap = toMap(array.getJSONObject(i)); jsonList.add(jsonMap); } return jsonList; } public static boolean validateDate(String date) { if(date == null ||date.trim().length() != 10) return false; else { date = date.trim(); String[] param = date.split("-"); if(param[0].length() != 4) return false; int month = Integer.parseInt(param[1]); if(month < 1 || month > 12) return false; int day = Integer.parseInt(param[2]); if(day < 1 || day > 31) return false; } return true; } @SuppressWarnings("unchecked") private static Object convertFromStringListSimple (String jsonValue,Class toClass) throws Exception { if( toClass == null) { return null; } ArrayList<Object> list = new ArrayList<Object>(); JSONArray array = new JSONArray(jsonValue); int i; Object value = null; for(i = 0; i < array.length(); i++) { Object property = array.get(i); if(java.util.Date.class.isAssignableFrom(toClass)) { String date = (String)property; if(!validateDate(date)){ throw new Exception("日期格式错误!"); } value = new SimpleDateFormat("yyyy-MM-dd").parse(date.trim()); } else if(java.sql.Date.class.isAssignableFrom(toClass)){ String date = (String)property; if(!validateDate(date)){ throw new Exception("日期格式错误!"); } value = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse( date.trim()).getTime()); } else value = OgnlOps.convertValue(property, toClass); list.add(value); } return list; } @SuppressWarnings("unchecked") private static Object convertFromStringListComplex( String jsonValue, Class toClass) throws Exception{ if( toClass == null) { return null; } ArrayList<Object> list = new ArrayList<Object>(); JSONArray array = new JSONArray(jsonValue); for (int i = 0; i < array.length(); i++) { Object obj = toClass.newInstance(); Map map = toMap(array.getJSONObject(i)); PropertyDescriptor[] props = OgnlUtil.getPropertyDescriptors(obj); for (PropertyDescriptor desc : props) { if( map.containsKey(desc.getName()) ) { Object value = null; // 处理日期型 // "yyyy-MM-dd'T'HH:mm:ss'Z'"此格式是由json2.js转换后的Date格式 if(java.util.Date.class.isAssignableFrom(desc.getPropertyType())) { String date = (String) map.get(desc.getName()); if(!validateDate(date)){ throw new Exception(desc.getName()+"日期格式错误!"); } value = new SimpleDateFormat("yyyy-MM-dd").parse(date.trim()); } else if(java.sql.Date.class.isAssignableFrom(desc.getPropertyType())) { String date = (String) map.get(desc.getName()); if(!validateDate(date)){ throw new Exception(desc.getName()+"日期格式错误!"); } value = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse( date.trim()).getTime()); } else { try{ value = OgnlOps.convertValue(map.get(desc.getName()), desc.getPropertyType()); }catch(NumberFormatException e){ Class clz = desc.getPropertyType(); if(clz == Integer.class||clz == Short.class||clz == Long.class||clz == BigInteger.class) throw new Exception(desc.getName()+"应为整数!"); else if(clz == Double.class||clz == Float.class||clz == BigDecimal.class) throw new Exception(desc.getName()+"应为数字!"); } } desc.getWriteMethod().invoke(obj, new Object[] { value }); } } list.add(obj); } return list; } @SuppressWarnings("unchecked") private static Map<String,Object> toMap(JSONObject object) throws Exception { HashMap<String, Object> map = new HashMap<String, Object>(); Iterator iter = object.keys(); while (iter.hasNext()) { String key = (String) iter.next(); Object val = object.get(key); if(val != null && !val.toString().trim().equals("")) map.put(key,val); } return map; } /** * 将javabean转成json字符串 * @param cls 要转的javabean类型 * @param value 要转的javabean * @return String * */ public static String bean2Json(Class<?> cls, Object value) { try { return transToJSONObject(cls, value).toString(); } catch (Exception e) { log.error("转换jsonObject失败",e); return null; } } // 将value转换成JSONObject @SuppressWarnings("unchecked") private static Object transToJSONObject(Class<?> cls, Object value) throws Exception { Object json = null; if (value != null) { if (Collection.class.isAssignableFrom(cls)) { // 列表s Iterator iter = ((Collection) value).iterator(); JSONArray array = new JSONArray(); while (iter.hasNext()) { Object element = iter.next(); if( element != null ) { array.put(transToJSONObject(element.getClass(), element)); } } json = array; } else if (cls.isArray()) { // 数组 JSONArray array = new JSONArray(); int length = Array.getLength(value); for (int i = 0; i < length; i++) { Object element = Array.get(value, i); if( element != null ) { array.put(transToJSONObject(element.getClass(), element)); } } json = array; } else if (Map.class.isAssignableFrom(cls)) { // 映射 Iterator iter = ((Map) value).entrySet().iterator(); JSONObject object = new JSONObject(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); Object v = entry.getValue(); if( v != null ) { object.put(entry.getKey().toString(), transToJSONObject(v.getClass(), v)); } } json = object; } else if (cls.isPrimitive() || CharSequence.class.isAssignableFrom(cls) || Number.class.isAssignableFrom(cls)) { // 基本类型、数值或字符串 if (cls == Boolean.TYPE || cls == Integer.TYPE || cls == Float.TYPE || cls == Double.TYPE || cls == Long.TYPE || cls == Short.TYPE || cls == Byte.TYPE || cls.isAssignableFrom(Number.class)) { json = value; } else { json = value.toString(); } } else if (java.util.Date.class.isAssignableFrom(cls) || java.sql.Date.class.isAssignableFrom(cls)) { json = value.toString(); } else { // 对象 Map map = OgnlUtil.getBeanMap(value); JSONObject object = new JSONObject(); if ( map != null ) { Iterator iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry element = (Map.Entry) iter.next(); Object v = element.getValue(); if( v != null ) { object.put((String)element.getKey(), transToJSONObject(v.getClass(), v)); }else{ object.put((String)element.getKey(), "null"); } } json = object; } } } return json == null ? "" : json; } @SuppressWarnings("unchecked") public static void main(String args[]) throws Exception{ String str = "[\"1\",\"2\",\"3\",\"4\"]"; ArrayList list = (ArrayList)JsonUtil.json2Bean(ArrayList.class, str, null); System.out.println(list.get(0)); } private static Log log = LogFactory.getLog(JsonUtil.class); }
发表评论
-
Hash算法原理
2011-08-30 18:21 759我来做一个比喻吧。 ... -
负载均衡的原理与算法介绍
2011-08-30 14:40 824服务器负载均衡算法 ... -
Apache Dos漏洞
2011-08-26 15:29 1048请大家注意下面这段: <IfModule m ... -
Quartz CronTrigger最完整配置说明
2011-08-24 17:06 589CronTrigger配置格式:格式: [秒] [分] [ ... -
常用正则表达式
2011-08-24 13:51 6351。^\d+$ //匹配非负整数(正整数 + 0) 2。 ... -
在WEB环境中使用ThreadLocal注意事项
2011-08-17 19:22 5225具体的ThreadLocal的原理,这里就不在累赘了 ... -
Http协议中的 session,cookia
2011-06-09 16:14 902HTTP协议(http://www.w3.org/ ... -
Google IO 2011最新技术分享
2011-06-09 09:15 980Google Io的视频讲解,基本是英文为主,中文或者英文字幕 ... -
怎么在webx3中取得cookie的值
2011-06-07 16:25 1059淘宝的session都是基于cookie的,怎么在webx3中 ... -
hessian的序列化问题
2011-06-07 15:29 1128最近在项目中发现一个很奇怪的问题,将ProductDraftD ...
相关推荐
java 对象与json字符串互相转换工具类所需要的jar,java 对象与json字符串互相转换工具类
NULL 博文链接:https://web4j.iteye.com/blog/1746838
java,android map形式和数组list转json字符串 可直接调用
- commons-beanutils-1.8.0.jar - commons-collections-3.1.jar - commons-lang-2.5.jar - commons-logging-1.2.jar - ezmorph-1.0.6.jar - json-lib-2.4-jdk15.jar
该工具类包括多重的json字符串或Map或List的相互转换,该文件包括主要的jar包,可以快捷的使用工具
解析JSON字符串成一个MAP、list、object和JAVA的类等转化成JSON语句。包括JSON相关的JAR
JSON官网上推荐的使用java解析json的类库,官网下载后的是未编译打包的java文件,这是我打包后的东东,使用时直接添加进Build path即可,简单实用……
json读取 java日期转换 字符串转换 各种类型互相转换 集合排序 日期处理等,别看分多,里边包含13中java常用的公用类,绝对物超所值。
工具类---实现实体类与Json的转换
本实例主要是通过json-libjar包中的工具类进行操作,简单实现了xml字符串和json字符串之间的转化,xml文件和json文件的转化。而且还兼容jsonObject和jsonArray两种格式,自己摸索,记录一下以便学习。
java使用fastJson处理复杂Json字符串,直接获取key对应的value值
json数据交互时作为校验是否通过,用于后台需要构建json返回前台必备
json常用的工具类,包含json字符串转对象,list和map等
Json字符串处理方法集成大类,帮助开发者快速开发程序。
一个工具类,提供JSON字符串与Java对象(实体Bean,Map,Collection,Object[])之间转换的方法,含有有demo、依赖包及源码,导入即可用。
写一个工具类,有两个方法,一个是输入类对象,输出类对象的json字符串,还有一个是输入json字符串和对象类型,输出类对象。 既然跟json有关,我开始百度了解json字符串: 百度是这样说的:JSON(JavaScript Object ...
同样先将json字符串转换为json对象,再将json对象转换为java对象,如下所示。 JSONObject obj = new JSONObject().fromObject(jsonStr);//将json字符串转换为json对象 将json对象转换为java对象 Person jb = (Person...
GeoJSON是一种对各种地理数据结构进行编码的格式,基于Javascript对象表示法(JavaScript Object Notation, 简称JSON)的地理空间信息数据交换格式...该工具可以实现通过java代码将任意的实体类数据集合生成GeoJSON字符串
支持maven引入依赖生成二维码,自带工具类,支持生成二维码到本地,也可以转成base64字符串(前端轻松解析),写好了强大的工具类,总有一个适合你的。。。。。
实现全局转换标准json格式的字符串的key值,亲测可用。