美文网首页
java 一个Map的使用帮助类

java 一个Map的使用帮助类

作者: 吃猫的鱼0 | 来源:发表于2018-02-02 11:11 被阅读0次
    package Pay.WeChatPay.Utils;
    
    import java.beans.BeanInfo;
    import java.beans.Introspector;
    import java.beans.PropertyDescriptor;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.io.UnsupportedEncodingException;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    import java.net.URLEncoder;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.LinkedHashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Set;
    
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    
    import org.w3c.dom.DOMException;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.NodeList;
    import org.xml.sax.SAXException;
    
    public class MapUtil {
    
        public static Map<String,Object> toMap(Object object){
            Map<String,Object> map = new HashMap<String, Object>();
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field field : fields) {
                Object obj;
                try {
                    obj = field.get(object);
                    if(obj!=null){
                        map.put(field.getName(), obj);
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            return map;
        }
        /**
         * Map转对象
         * @param map
         * @param beanClass
         * @return
         * @throws Exception
         */
           public static Object mapToObject(Map<String, Object> map, Class<?> beanClass)  {    
                if (map == null)   
                    return null;    
                Object obj = null;
              try {
                     obj = beanClass.newInstance();  
          
                BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());    
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();    
                for (PropertyDescriptor property : propertyDescriptors) {  
                    Method setter = property.getWriteMethod();    
                    if (setter != null) {  
                        setter.invoke(obj, map.get(property.getName()));   
                    }  
                }  
                } catch (Exception e) {
                    return null;
                }
          
                return obj;  
            }   
        /**
         * 使用key对map排序
         * @param map
         * @return
         */
        public static Map<String,String> orderByKey(Map<String, String> map){
            HashMap<String, String> tempMap = new LinkedHashMap<String, String>();
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>( map.entrySet());
    
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
                public int compare(Map.Entry<String, String> o1,Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
    
            for (int i = 0; i < infoIds.size(); i++) {
                Map.Entry<String, String> item = infoIds.get(i);
                tempMap.put(item.getKey(), item.getValue());
            }
            return tempMap;
        }
    
        
        /**
         * 转换对象为map
         * @param object        对象
         * @param ignore        不添加的属性数组
         * @return
         */
        public static Map<String,String> objectToMap(Object object,String... ignore){
            Map<String,String> tempMap = new LinkedHashMap<String, String>();
            for(Field f : object.getClass().getDeclaredFields()){//获取反射所有申明的字段
                if(!f.isAccessible()){
                    f.setAccessible(true);//启用和禁用访问安全检查的开关,并不是为true就能访问为false就不能访问
                }
                boolean ig = false;
                if(ignore!=null&&ignore.length>0){
                    for(String i : ignore){
                        if(i.equals(f.getName())){
                            ig = true;
                            break;
                        }
                    }
                }
                if(ig){
                    continue;
                }else{
                    Object o = null;
                    try {
                        o = f.get(object);//拿到object实例的值
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    tempMap.put(f.getName(), o==null?"":o.toString());//制作成键值对
                }
            }
            return tempMap;
        }
    
        /**
         * url 参数串连
         * @param map
         * @param keyLower
         * @param valueUrlencode
         * @return
         */
        public static String mapJoin(Map<String, String> map,boolean keyLower,boolean valueUrlencode){
            StringBuilder stringBuilder = new StringBuilder();
            for(String key :map.keySet()){
                if(map.get(key)!=null&&!"".equals(map.get(key))){
                    try {
                        String temp = (key.endsWith("_")&&key.length()>1)?key.substring(0,key.length()-1):key;
                        stringBuilder.append(keyLower?temp.toLowerCase():temp)
                                     .append("=")
                                     .append(valueUrlencode?URLEncoder.encode(map.get(key),"utf-8").replace("+", "%20"):map.get(key))
                                     .append("&");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
            if(stringBuilder.length()>0){
                stringBuilder.deleteCharAt(stringBuilder.length()-1);
            }
            return stringBuilder.toString();
        }
    
        /**
         * 简单 xml 转换为 Map
         * @param reader
         * @return
         */
        public static Map<String,String> xmlToMap(String xml){
            try {
                DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                Document document = documentBuilder.parse(new ByteArrayInputStream(xml.getBytes()));
                Element element = document.getDocumentElement();
                NodeList nodeList = element.getChildNodes();
                Map<String, String> map = new LinkedHashMap<String, String>();
                for(int i=0;i<nodeList.getLength();i++){
                    Element e = (Element) nodeList.item(i);
                    map.put(e.getNodeName(),e.getTextContent());
                }
                return map;
            } catch (DOMException e) {
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        /**
         * 将map转xml
         * @param map
         * @param sb
         * @return
         */
        @SuppressWarnings("rawtypes")
         public static String mapToXML(Map map, StringBuffer sb) {  
                Set set = map.keySet();  
                sb.append("<xml>");  
                for (Iterator it = set.iterator(); it.hasNext();) {  
                    String key = (String) it.next();  
                    Object value = map.get(key);  
                    if (null == value)  
                        value = "";  
                    if (value.getClass().getName().equals("java.util.ArrayList")) {  
                        ArrayList list = (ArrayList) map.get(key);  
                        sb.append("<" + key + ">");  
                        for (int i = 0; i < list.size(); i++) {  
                            HashMap hm = (HashMap) list.get(i);  
                            mapToXML(hm, sb);  
                        }  
                        sb.append("</" + key + ">");  
          
                    } else {  
                        if (value instanceof HashMap) {  
                            sb.append("<" + key + ">");  
                            mapToXML((HashMap) value, sb);  
                            sb.append("</" + key + ">");  
                        } else {  
                            sb.append("<" + key + ">" + value + "</" + key + ">");  
                        }                   
                    }     
                }  
                sb.append("</xml>");  
               return sb.toString();
            }  
         /**
          * 将map转成xmlstr
          * @param map
          * @return
          */
         public static String mapToXmlStr(Map<String, String> map){  
                String xmlStr = null;  
                StringBuffer sbf = new StringBuffer();  
                sbf.append("<xml>");  
                for(Entry<String, String> s: map.entrySet()){  
                      
                    sbf.append("<")  
                        .append(s.getKey())  
                        .append(">")  
                        .append(s.getValue())  
                        .append("</")  
                        .append(s.getKey())  
                        .append(">");  
                          
                }  
                sbf.append("</xml>");  
                xmlStr = sbf.toString();  
                return xmlStr;  
            }  
    }
    

    相关文章

      网友评论

          本文标题:java 一个Map的使用帮助类

          本文链接:https://www.haomeiwen.com/subject/wjbuoxtx.html