随笔

(持续更新)
Map转XML

 public static String MapToXML(Map<String, String> params) throws ParserConfigurationException{
        Class<PreReqParamsModel> clazz = PreReqParamsModel.class;
        Field[] fields = clazz.getDeclaredFields();
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
        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("http://javax.xml.XMLConstants/feature/secure-processing", true);
        documentBuilderFactory.setXIncludeAware(false);
        documentBuilderFactory.setExpandEntityReferences(false);
        org.w3c.dom.Document document = documentBuilderFactory.newDocumentBuilder().newDocument();
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key: params.keySet()) {
            String value = params.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = null;
		try {
			transformer = tf.newTransformer();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		}
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        try {
			transformer.transform(source, result);
		} catch (TransformerException e) {
			e.printStackTrace();
		}
        String output = writer.getBuffer().toString(); 
        try {
            writer.close();
        }
        catch (Exception ex) {
        }
        return output;
    }

Pojo(实体类)转XML

public static String generateXMLByPreReqParamsModel(ParamsPojo  params) throws ParserConfigurationException{
     	Class<ParamsPojo  > clazz = ParamsPojo  .class;
        Field[] fields = clazz.getDeclaredFields();
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
        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("http://javax.xml.XMLConstants/feature/secure-processing", true);
        documentBuilderFactory.setXIncludeAware(false);
        documentBuilderFactory.setExpandEntityReferences(false);
        org.w3c.dom.Document document = documentBuilderFactory.newDocumentBuilder().newDocument();
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for(Field f:fields){
            f.setAccessible(true);
            Object obj;
            try{
                obj = f.get(params);
                if(obj!=null){
                	org.w3c.dom.Element filed = document.createElement(f.getName());
                    filed.appendChild(document.createTextNode(obj.toString()));
                    root.appendChild(filed);
                }
            }catch (IllegalArgumentException e){
                e.printStackTrace();
            }catch (IllegalAccessException e){
                e.printStackTrace();
            }
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = null;
		try {
			transformer = tf.newTransformer();
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        try {
			transformer.transform(source, result);
		} catch (TransformerException e) {
			e.printStackTrace();
		}
        String output = writer.getBuffer().toString(); 
        try {
            writer.close();
        }
        catch (Exception ex) {
        }
        return output;
    }

xml形式的String转Map

public static Map xmlStrToMap(String strXML) throws Exception {
    	   Map data = new HashMap<Object, Object>();
    	   System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
 	       DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
    	   String FEATURE = null;
    	   try {
    		  FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
    	      documentBuilderFactory.setFeature(FEATURE, true);

    	      FEATURE = "http://xml.org/sax/features/external-general-entities";
    	      documentBuilderFactory.setFeature(FEATURE, false);

    	      FEATURE = "http://xml.org/sax/features/external-parameter-entities";
    	      documentBuilderFactory.setFeature(FEATURE, false);

    	      FEATURE = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
    	      documentBuilderFactory.setFeature(FEATURE, false);

    	      documentBuilderFactory.setXIncludeAware(false);
    	      documentBuilderFactory.setExpandEntityReferences(false);

    	   } catch (ParserConfigurationException e) {
    	      System.out.println("ParserConfigurationException was thrown. The feature '" +
    	            FEATURE + "' is probably not supported by your XML processor.");

    	   }
    	   DocumentBuilder documentBuilder= documentBuilderFactory.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) {

    	   }
    	   return data;
    	}

将请求参数封装为Map

public static Map getParamAsMap(HttpServletRequest request) {
			Map<String,String> requestMap=new HashMap<String,String>();
			Map map = request.getParameterMap();
			if(map.values()!=null){
				Iterator<Object> keyIterator = (Iterator<Object>) map.keySet().iterator();
				while (keyIterator.hasNext()) {
					String key = (String) keyIterator.next();
					if(!"_".equals(key)){
						String value = ((String[]) (map.get(key)))[0];
						requestMap.put(key, value);
					}
				}
			}
			return requestMap;
		}

将对象转为json字符串

public class JsonHelp {
	private static final SerializeConfig   config; 
	static { 
	    config = new SerializeConfig(); 
	    config.put(java.util.Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss")); // 使用和json-lib兼容的日期输出格式 
	} 
	private static final SerializerFeature[] features = { 
			SerializerFeature.WriteMapNullValue, // 输出空置字段 
	        SerializerFeature.WriteNullListAsEmpty, // list字段如果为null,输出为[],而不是null
	        SerializerFeature.WriteNullNumberAsZero, // 数值字段如果为null,输出为0,而不是null 
	        SerializerFeature.WriteNullBooleanAsFalse, // Boolean字段如果为null,输出为false,而不是null 
	        SerializerFeature.WriteNullStringAsEmpty // 字符类型字段如果为null,输出为"",而不是null 
	}; 
	public static String ObjectToJson(Object object) {
		return JSON.toJSONString(pObject,config,features);
	}
}

此方法需要jar:
commons-beanutils.jar
commons-collections.jar
commons-lang.jar
ezmorph.jar
fastjson.jar
等等
HashMap根据默认key值的首字母大小顺序进行存储;
LinkedHashMap可以保证按put()调用的先后顺序进行存储;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值