zoukankan      html  css  js  c++  java
  • map转实体类,下划线隔开转驼峰式命名;map转xml;xml转map;转换

    map转实体类,下划线隔开转驼峰式命名;

    package com.eoma.autocoding.utils;
    
    import com.eoma.autocoding.common.Table;
    
    import java.lang.reflect.Field;
    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Set;
    
    public class MapToObject {
    
        public static void main(String[] args) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("name","1");
            map.put("dbName","2");
            map.put("table_desc","3");
            Table detail = new Table();
            System.out.println(mapToObj(map,detail));
        }
        /**
         * 只支持下划线隔开、驼峰式属性名(用之前请测试)
         * @param map
         * @param t
         * @param <T>
         * @return
         */
        public static <T>  T  mapToObj(Map<String ,?> map, T t){
            Set<String> keySet = map.keySet();
            keySet.forEach(s->{
                Object value = map.get(s);
                String name = toCamelCase(s);
                Field[] declaredFields = t.getClass().getDeclaredFields();
                Arrays.stream(declaredFields).filter(d->d.getName().equalsIgnoreCase(name)).forEach(field ->{
                    try {
                        field.setAccessible(true);
                        field.set(t,value);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            });
    
            return t;
        }
    
        /**
         * 下划线隔开转驼峰式命名
         * @param str
         * @return
         */
        public static String toCamelCase(String str) {
            if (str == null || "".equals(str.trim())) {
                return null;
            } else {
                str = str.toLowerCase();
                StringBuilder sb = new StringBuilder(str.length());
                boolean upperCase = false;
                for (int i = 0; i < str.length(); i++) {
                    char c = str.charAt(i);
                    if (c == '_') {
                        if( i == 0 ){
                            sb.append(c);
                        }else{
                            upperCase = true;
                        }
                    } else if (upperCase) {
                        sb.append(Character.toUpperCase(c));
                        upperCase = false;
                    } else {
                        sb.append(c);
                    }
                }
                return sb.toString();
            }
        }
    }

    map转xml;

        public static String mapToXml(HashMap<String,Object> paraMap){
            StringBuffer sb = new StringBuffer();
            sb.append("<xml>");
            Set es = paraMap.entrySet();
            Iterator it = es.iterator();
            while (it.hasNext()) {
                Map.Entry entry = (Map.Entry) it.next();
                String k = (String) entry.getKey();
                Object v =            entry.getValue();
                if (null != v && !"key".equals(k)) {
                    sb.append("<"+k+">" + v +"</"+k+">");
                }
            }
            sb = sb.append("</xml>");
            return sb.toString();
        }

    xml转map;

        /**
         * XML格式字符串转换为Map
         *
         * @param strXML XML字符串
         * @return XML数据转换后的Map
         * @throws Exception
         */
        public static Map<String, String> xmlToMap(String strXML) throws Exception {
            try {
                Map<String, String> data = new HashMap<String, String>();
                DocumentBuilder documentBuilder =newDocumentBuilder();
                InputStream stream = new ByteArrayInputStream(strXML.getBytes("UTF-8"));
                org.w3c.dom.Document doc = documentBuilder.parse(stream);
                doc.getDocumentElement().normalize();
                NodeList nodeList = doc.getDocumentElement().getChildNodes();
                for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                    Node node = nodeList.item(idx);
                    if (node.getNodeType() == Node.ELEMENT_NODE) {
                        org.w3c.dom.Element element = (org.w3c.dom.Element) node;
                        data.put(element.getNodeName(), element.getTextContent());
                    }
                }
                try {
                    stream.close();
                } catch (Exception ex) {
                    // do nothing
                }
                return data;
            } catch (Exception ex) {
                throw ex;
            }
    
        }
    
    
    
    
        public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
            documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
            documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
            documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            documentBuilderFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
            documentBuilderFactory.setXIncludeAware(false);
            documentBuilderFactory.setExpandEntityReferences(false);
    
            return documentBuilderFactory.newDocumentBuilder();
        }
  • 相关阅读:
    求连续子数组的最大和
    【LeetCode练习题】Gas Station
    再来看看快速排序
    【LeetCode练习题】First Missing Positive
    【LeetCode练习题】Merge Sorted Array
    Hdu 2089-不要62 数位dp
    Tsinsen A1517. 动态树 树链剖分,线段树,子树操作
    Bzoj 3505: [Cqoi2014]数三角形 数论
    Poj 3695-Rectangles 矩形切割
    Tsinsen A1505. 树(张闻涛) 倍增LCA,可持久化线段树,DFS序
  • 原文地址:https://www.cnblogs.com/qq376324789/p/14831062.html
Copyright © 2011-2022 走看看