JOSN,XML,MAP相互轉換,MAP和Bean轉換
阿新 • • 發佈:2018-11-09
直接貼程式碼
JOSN,XML,MAP相互轉換
import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import net.sf.json.JSONObject; /** * * 提供Map<String,Object>轉XML,XML轉Map<String,Object> * Map<String,Object>轉Json,Json轉Map<String,Object> * XML轉Json,Json轉XML * * @author MOSHUNWEI * @since 2018-03-09 * @version 5.0 */ public class JXMUtils { /** * * 通過Map建立XML,Map可以多層轉換獲一層轉換 * * @param params * @return String-->XML */ public static String createXmlByMap(String parentName,Map<String, Object> params,boolean isFormXml){ Document doc = DocumentHelper.createDocument(); doc.addElement(parentName); String xml = iteratorXml(doc.getRootElement(),parentName,params,false); if(isFormXml){ return formatXML(xml); }else{ return xml; } } /** * * 通過Map建立XML,Map可以多層轉換獲一層轉換text格式有DATA * * @param params * @return String-->XML */ public static String createXmlByMap(String parentName,Map<String, Object> params,boolean isCDATA,boolean isFormXml){ Document doc = DocumentHelper.createDocument(); doc.addElement(parentName); String xml = iteratorXml(doc.getRootElement(),parentName,params,isCDATA); if(isFormXml){ return formatXML(xml); }else{ return xml; } } /** * * MapToXml迴圈遍歷建立xml節點 * * @param element 根節點 * @param parentName 子節點名字 * @param params map資料 * @return String-->Xml */ @SuppressWarnings("unchecked") private static String iteratorXml(Element element,String parentName,Map<String,Object> params,boolean isCDATA) { Element e = element.addElement(parentName); Set<String> set = params.keySet(); for (Iterator<String> it = set.iterator(); it.hasNext();) { String key = (String) it.next(); if(params.get(key) instanceof Map) { iteratorXml(e,key,(Map<String,Object>)params.get(key),isCDATA); }else if(params.get(key) instanceof List){ List<Map<String,Object>> list = (List<Map<String, Object>>) params.get(key); for(Map<String,Object> en : list){ iteratorXml(e, key, en, isCDATA); } }else { String value = params.get(key)==null?"":params.get(key).toString(); if(!isCDATA) { e.addElement(key).addText(value); }else { e.addElement(key).addCDATA(value); } } } return e.asXML(); } /** * 格式化xml,顯示為容易看的XML格式 * * @param inputXML * @return */ public static String formatXML(String inputXML){ Document document = null; try { SAXReader reader = new SAXReader(); document = reader.read(new StringReader(inputXML)); return formatXML(document); } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * 格式化document,顯示為容易看的XML格式 * * @param inputXML * @return */ public static String formatXML(Document document){ String requestXML = null; XMLWriter writer = null; try { if (document != null) { StringWriter stringWriter = new StringWriter(); OutputFormat format = new OutputFormat(" "); format.setEncoding("UTF-8"); format.setIndent(true); format.setSuppressDeclaration(false); //不生成xml名稱空間 format.setNewLineAfterDeclaration(false); format.setNewlines(true); writer = new XMLWriter(stringWriter, format); writer.write(document); writer.flush(); requestXML = stringWriter.getBuffer().toString(); } return requestXML; } catch (Exception e1) { e1.printStackTrace(); return null; }finally { if (writer != null) { try { writer.close(); } catch (IOException e) { } } } } /** * 去掉空間命名的xml * * @param inputXML * @return */ public static String formatXMLNotHead(String inputXML){ return inputXML.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n", ""); } /** * * 通過XML轉換為Map<String,Object> * * @param xml 為String型別的Xml * @return 第一個為Root節點,Root節點之後為Root的元素,如果為多層,可以通過key獲取下一層Map */ public static Map<String, Object> createMapByXml(String xml) { Document doc = null; try { doc = DocumentHelper.parseText(xml); } catch (DocumentException e) { e.printStackTrace(); } return createMapByDocument(doc); } /** * * 通過document轉換為Map<String,Object> * * @return */ public static Map<String, Object> createMapByDocument(Document doc) { Map<String, Object> map = new HashMap<String, Object>(); if (doc == null) return map; Element rootElement = doc.getRootElement(); elementTomap(rootElement,map); return map; } /*** * * XmlToMap核心方法,裡面有遞迴呼叫 * * @param map * @param ele */ @SuppressWarnings("unchecked") private static Map<String, Object> elementTomap (Element outele,Map<String,Object> outmap) { List<Element> list = outele.elements(); int size = list.size(); if(size == 0){ outmap.put(outele.getName(), outele.getTextTrim()); }else{ Map<String, Object> innermap = new HashMap<String, Object>(); for(Element ele1 : list){ String eleName = ele1.getName(); Object obj = innermap.get(eleName); if(obj == null){ elementTomap(ele1,innermap); }else{ if(obj instanceof java.util.Map){ List<Map<String, Object>> list1 = new ArrayList<Map<String, Object>>(); list1.add((Map<String, Object>) innermap.remove(eleName)); elementTomap(ele1,innermap); list1.add((Map<String, Object>) innermap.remove(eleName)); innermap.put(eleName, list1); }else{ elementTomap(ele1,innermap); ((List<Map<String, Object>>)obj).add(innermap); } } } outmap.put(outele.getName(), innermap); } return outmap; } /** * 返回格式化JSON字串。 * * @param json 未格式化的JSON字串。 * @return 格式化的JSON字串。 */ public static String formatJson(String json){ StringBuffer result = new StringBuffer(); int length = json.length(); int number = 0; char key = 0; for (int i = 0; i < length; i++){ key = json.charAt(i); if((key == '[') || (key == '{') ){ if((i - 1 > 0) && (json.charAt(i - 1) == ':')) { result.append('\n'); result.append(indent(number)); } result.append(key); result.append('\n'); number++; result.append(indent(number)); continue; } if((key == ']') || (key == '}') ){ result.append('\n'); number--; result.append(indent(number)); result.append(key); if(((i + 1) < length) && (json.charAt(i + 1) != ',')){ result.append('\n'); } continue; } if((key == ',')){ result.append(key); result.append('\n'); result.append(indent(number)); continue; } result.append(key); } return result.toString(); } /** * 返回指定次數的縮排字串。每一次縮排三個空格,即SPACE。 * * @param number 縮排次數。 * @return 指定縮排次數的字串。 */ private static String indent(int number){ StringBuffer result = new StringBuffer(); for(int i = 0; i < number; i++){ result.append(" "); } return result.toString(); } /** * map轉為json * @param map * @return */ public static String mapToJson(Map<String,Object> map,boolean isFormJson){ String json = JSONObject.fromObject(map).toString(); if(isFormJson){ return formatJson(json); }else{ return json; } } /** * json轉為map * @param json * @return */ public static Map<String,Object> jsonToMap(String json){ @SuppressWarnings("unchecked") Map<String,Object> map = new HashMap<>(JSONObject.fromObject(json)); return map; } /** * map轉xml * @param json * @return */ public static String jsonToXml(String json,boolean isFormXml){ Map<String, Object> map = jsonToMap(json); return createXmlByMap("Document", map,isFormXml); } /** * xml轉map * @param xml * @return */ public static String xmlToJson(String xml,boolean isFormJson){ Map<String, Object> map = createMapByXml(xml); return mapToJson(map,isFormJson); } }
MAP和Bean轉換
import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class BeanUtils { protected final static Log logger = LogFactory.getLog(BeanUtils.class.getClass()); public static Map<String,Object> transMap2Bean(Object obj){ Map<String,Object> map = new HashMap<String,Object>(); try{ BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for(PropertyDescriptor property: descriptors){ String key = property.getName(); if (!key.equals("class")) { // 得到property對應的getter方法 Method getter = property.getReadMethod(); Object value = getter.invoke(obj); map.put(key, value); } } }catch (Exception e) { logger.info("bean轉map失敗!"); } return map; } public static <T extends Object> T transMap2Bean(Map<String,Object> map,Class<T> clazz){ T instance = null; try{ instance = clazz.newInstance(); BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : descriptors) { String key=property.getName(); if(map.containsKey(key)){ Object value = map.get(key); Method setter = property.getWriteMethod(); setter.invoke(instance, value); } } }catch (Exception e) { logger.info("map轉bean失敗!"); } return instance; }