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;
}
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;
}
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;
}
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;
}
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()调用的先后顺序进行存储;