• 公用方法的一些转换


    1  json对象转换成实体

    //json对象转换成实体
    	public static <T> T JSONObjectToEntity(JSONObject obj,T entity){
    		Field[] fields = entity.getClass().getDeclaredFields(); // 获取实体类的所有属
    		 try {
    	            for (int j = 0; j < fields.length; j++) { // 遍历所有属性
    	                String name = fields[j].getName(); // 获取属性的名字
    	                //判断JSONObject是否包含该字段
    	                if(!obj.containsKey(name)){
    	                	continue;
    	                }
    	                String param=obj.getString(name); //获取JSONObject里的值
    	                name = name.substring(0, 1).toUpperCase() + name.substring(1); // 将属性的首字符大写,方便构造get,set方法
    	                String type = fields[j].getGenericType().toString(); // 获取属性的类型
    	                if (type.equals("class java.lang.String")) { // 如果type是类类型,则前面包含"class ",后面跟类名
    	                    Method m = entity.getClass().getMethod("set"+name,String.class);
    	                    m.invoke(entity, param);
    	                }
    	                if (type.equals("class java.lang.Integer")) {
    	                    Method m = entity.getClass().getMethod("set"+name,Integer.class);
    	                    m.invoke(entity, Integer.parseInt(param));
    	                }
    	                if (type.equals("class java.lang.Boolean")) {
    	                    Method m = entity.getClass().getMethod("set"+name,Boolean.class);
    	                        m.invoke(entity, Boolean.valueOf(param));
    	                }
    	                if (type.equals("class java.util.Date")) {
    	                	Date date=dateFormat1.parse(param);
    	                    Method m = entity.getClass().getMethod("set"+name,Date.class);
    	                        m.invoke(entity,date);
    	                }
    	                // 如果有需要,可以仿照上面继续进行扩充,再增加对其它类型的判断
    	            }
    	        } catch (NoSuchMethodException e) {
    	        	log("JSONObject转换成实体出现异常:" + CommonUtil.getFormatTime(new java.util.Date(),"-")
    						+ e.getMessage(),"ERROR");
    	        } catch (SecurityException e) {
    	        	log("JSONObject转换成实体出现异常:" + CommonUtil.getFormatTime(new java.util.Date(),"-")
    						+ e.getMessage(),"ERROR");
    	        } catch (IllegalAccessException e) {
    	        	log("JSONObject转换成实体出现异常:" + CommonUtil.getFormatTime(new java.util.Date(),"-")
    						+ e.getMessage(),"ERROR");
    	        } catch (IllegalArgumentException e) {
    	        	log("JSONObject转换成实体出现异常:" + CommonUtil.getFormatTime(new java.util.Date(),"-")
    						+ e.getMessage(),"ERROR");
    	        } catch (InvocationTargetException e) {
    	        	log("JSONObject转换成实体出现异常:" + CommonUtil.getFormatTime(new java.util.Date(),"-")
    						+ e.getMessage(),"ERROR");
    	        } catch (ParseException e) {
    	        	log("JSONObject转换成实体出现异常:" + CommonUtil.getFormatTime(new java.util.Date(),"-")
    						+ e.getMessage(),"ERROR");
    			}
    		return entity;
    	}

    2 将实体转换成map

    //将实体转换成map
    	public static <T> Map<String,Object> beanToMap(T bean){
    		Map<String,Object> map=new HashMap<String,Object>();
    		Field[] fields = bean.getClass().getDeclaredFields(); // 获取实体类的所有属
    		try {
                for (int j = 0; j < fields.length; j++) { // 遍历所有属性
                    String name = fields[j].getName(); // 获取属性的名字
                    String UpperName = name.substring(0, 1).toUpperCase() + name.substring(1); // 将属性的首字符大写,方便构造get,set方法
                    String type = fields[j].getGenericType().toString(); // 获取属性的类型
                    if (type.equals("class java.lang.String")) { // 如果type是类类型,则前面包含"class ",后面跟类名
                        Method m = bean.getClass().getMethod("get" + UpperName);
                        String value = (String) m.invoke(bean); // 调用getter方法获取属性值
                        if (value == null) {
                           map.put(name, "");
                        }else{
                        	map.put(name, value);
                        }
                    }
                    if (type.equals("class java.lang.Integer")) {
                        Method m = bean.getClass().getMethod("get" + UpperName);
                        Integer value = (Integer) m.invoke(bean);
                        if (value == null) {
                            map.put(name, 0);
                         }else{
                         	map.put(name, value);
                         }
                    }
                    if (type.equals("class java.lang.Boolean")) {
                        Method m = bean.getClass().getMethod("get" + UpperName);
                        Boolean value = (Boolean) m.invoke(bean);
                        if (value == null) {
                            map.put(name, false);
                         }else{
                         	map.put(name, value);
                         }
                    }
                    if (type.equals("class java.util.Date")) {
                        Method m = bean.getClass().getMethod("get" + UpperName);
                        Date value = (Date) m.invoke(bean);
                        if (value == null) {
                            map.put(name, new Date());
                         }else{
                         	map.put(name, value);
                         }
                    }
                    // 如果有需要,可以仿照上面继续进行扩充,再增加对其它类型的判断
                }
            } catch (NoSuchMethodException e) {
            	log("实体转换成map出现异常:" + CommonUtil.getFormatTime(new java.util.Date(),"-")
    					+ e.getMessage(),"ERROR");
            } catch (SecurityException e) {
            	log("实体转换成map出现异常:" + CommonUtil.getFormatTime(new java.util.Date(),"-")
    					+ e.getMessage(),"ERROR");
            } catch (IllegalAccessException e) {
            	log("实体转换成map出现异常:" + CommonUtil.getFormatTime(new java.util.Date(),"-")
    					+ e.getMessage(),"ERROR");
            } catch (IllegalArgumentException e) {
            	log("实体转换成map出现异常:" + CommonUtil.getFormatTime(new java.util.Date(),"-")
    					+ e.getMessage(),"ERROR");
            } catch (InvocationTargetException e) {
            	log("实体转换成map出现异常:" + CommonUtil.getFormatTime(new java.util.Date(),"-")
    					+ e.getMessage(),"ERROR");
            } 
    		return map;
    	}
    3 将中文转换成utf-8

    	//将中文转换成utf-8
    	public static String encodeUTF8(String xmlDoc){
    		String str="";
    		try {
    			str=URLEncoder.encode(xmlDoc,"utf-8");
    			return str;
    		} catch (Exception e) {
    			str=e.toString();
    		}
    		return str;
    	}

    4 将utf-8转换成中文字符

    //将utf-8转换成中文字符
    	public static String decodeUTF8(String str){
    		String xmlDoc="";
    		try {
    			xmlDoc=URLDecoder.decode(str,"utf-8");
    			return xmlDoc;
    		} catch (Exception e) {
    			xmlDoc=e.toString();
    		}
    		return xmlDoc;
    	}

    5 对于登录等输入操作进行殊字符判断

    //对于登录等输入操作进行殊字符判断
    	public static boolean sql_inj(String str) {
    		String inj_str = "':and:exec:insert:select:delete:update:count:*:%:chr:mid:master:truncate:char:declare:;:or 1:-:+:,";
    		String inj_stra[] = inj_str.split(":");
    		for (int i = 0; i < inj_stra.length; i++) {
    			if (str.indexOf(inj_stra[i])!=-1) {
    				return false;
    			}
    		}
    		return true;
    	}

    6 xml转化为string

    /**
    	 * @Description:xml转化为string
    	 * Author: 
    	 * Date: 2016/3/27
    	 * Time: 19:53
    	 * Version: 0.1
    	 * document转换成string
    	 * @param document
    	 * @return
    	 */
    	public String toStringFromDoc(Document document) {
    		String result = null;
    		if (document != null) {
    			StringWriter strWtr = new StringWriter();
    			StreamResult strResult = new StreamResult(strWtr);
    			TransformerFactory tfac = TransformerFactory.newInstance();
    			try {
    				Transformer t = tfac.newTransformer();
    				t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    				t.setOutputProperty(OutputKeys.INDENT, "yes");
    				t.setOutputProperty(OutputKeys.METHOD, "xml"); // xml, html,text
    				t.setOutputProperty(
    						"{http://xml.apache.org/xslt}indent-amount", "4");
    				t.transform(new DOMSource(document.getDocumentElement()),
    						strResult);
    			} catch (Exception e) {
    				log(e);
    			}
    			result = strResult.getWriter().toString();
    			try {
    				strWtr.close();
    			} catch (IOException e) {
    				log(e);
    			}
    		}
    		return result;
    	}

    7 根据string 生成xml文件

    /**
    	 * @Description:根据string 生成xml文件
    	 * Author: 
    	 * Date: 2016/3/27
    	 * Time: 19:53
    	 * Version: 0.1
    	 * @param xmlString
    	 * @param fileName
         */
    	public void buildXmlFile(String xmlString,String fileName){
    		try{
    			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    			// step 2:获得具体的dom解析器
    			DocumentBuilder db = dbf.newDocumentBuilder();
    			StringReader stringReader  =  new StringReader(xmlString);
    			InputSource  inputSource  =  new InputSource(stringReader);
    			Document  newDoc  =  db.parse(inputSource ) ;
    			TransformerFactory tfactory=TransformerFactory.newInstance();
    			Transformer transformer=tfactory.newTransformer();
    			DOMSource source=new DOMSource(newDoc);
    			StreamResult result=new StreamResult(new File(fileName));
    //	        transformer.setOutputProperty("encoding","UTF-8");
    			transformer.transform(source,result);
    		}catch (Exception e) {
    			log(e);
    		}
    
    	}

    8 xml转换为json格式的数据

    /**
    	 * @Description:xml转换为json格式的数据
    	 * Author: 
    	 * Date: 2016/3/27
    	 * Time: 19:53
    	 * Version: 0.1
    	 * @param path
         * @return
         */
    	public static String toJson(String path) {
    		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    		// step 2:获得具体的dom解析器
    		DocumentBuilder db = null;
    		Document document = null;
    		try {
    			db = dbf.newDocumentBuilder();
    			document = db.parse(new File(path));
    		} catch (ParserConfigurationException e) {
    			e.printStackTrace();
    		} catch (SAXException e) {
    			e.printStackTrace();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		// step3: 解析一个xml文档,获得Document对象(根结点)
    		NodeList list = document.getElementsByTagName("Graphics");
    		Element rootElement = (Element)list.item(0);
    		NodeList nodeList = rootElement.getElementsByTagName("Graphic");
    		StringBuilder json = new StringBuilder("{"Graphic":[");//
    		if(nodeList != null){
    			for (int i = 0 ; i < nodeList.getLength(); i++){
    				Element element = (Element)nodeList.item(i);
    				String content = element.getElementsByTagName("Content").item(0).getFirstChild().getNodeValue();
    				if(i==0){
    					json.append(content);
    				}else{
    					json.append(","+content);
    				}
    
    			}
    		}
    		json.append("]}");
    		return json.toString();
    	}

    9 日期加减

    /**
    	 * 日期加减
    	 * @param date 传入的日期
    	 * @param days 加减的天数
    	 * @return 新的日期
    	 */
    	public static Date getNewDay(Date date,int days){
    		Date retDate = new Date();
    		try {
    		    retDate = new Date(date.getTime() + ((-days) * 24 * 60 * 60 * 1000));
    		} catch (Exception e) {
    			CommonUtil.log(e);
    		}
    		return retDate;
    	}

  • 相关阅读:
    ios开发之 -- 自动轮播图创建
    swift开发之 -- 自动轮播图(UIScrollView+UIPageControl+Timer)
    HTML5开发之 -- 模态突出窗(bootstrap)
    ios开发之--UICollectionView的使用
    ios开发之--判断奇偶数
    swift开发之 -- ? 和 ! 的作用
    swift开发之--UISearchBar的使用/UISearchController的使用
    swift开发之--报错:Class "***ViewController" has no initializers
    Android开发相关
    沁园春·雪
  • 原文地址:https://www.cnblogs.com/t0404/p/10290956.html
Copyright © 2020-2023  润新知