XML与JSON互转网上找了一圈,都有所失真,被逼无奈只好自己写一个。
注:xml->json->xml基本保持结构不变,json->xml->json会有所失真,因为json空数组节点会被丢弃。
用到的包:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>org.dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>2.1.1</version>
</dependency>
直接上代码了:
package cc.leowoo.frame.common.util;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class XmlJsonUtils {
private static final Logger logger = LoggerFactory.getLogger(XmlJsonUtils.class);
public final static String arrtsign = "@";
public final static String textsign = "#text";
public static String xmlToJson(String xml) throws Exception {
Document document = DocumentHelper.parseText(xml);
Element nodeElement = document.getRootElement();
JSONObject json = new JSONObject();
convertXMLToJson(nodeElement, json);
return json.toString();
}
private static void convertXMLToJson(Element nodeElement, JSONObject json) {
JSONObject jsonnode = new JSONObject();
Map<String, JSONArray> temp = new HashMap<String, JSONArray>();
String nodename = nodeElement.getName();
for (Iterator<Attribute> it = nodeElement.attributeIterator(); it.hasNext();) {
Attribute attr = it.next();
jsonnode.put(arrtsign + attr.getName(), attr.getValue());
}
String text = nodeElement.getTextTrim();
if (!"".equals(text)) {
jsonnode.put(textsign, nodeElement.getTextTrim());
}
if (nodeElement.elements().size() > 0) {
for (Iterator<Element> it = nodeElement.elementIterator(); it.hasNext();) {
Element node = it.next();
String name = node.getName();
if (!temp.containsKey(name)) {
temp.put(name, new JSONArray());
}
JSONObject tmpnode = new JSONObject();
convertXMLToJson(node, tmpnode);
if (tmpnode.get(name).getClass().equals(JSONObject.class) && tmpnode.getJSONObject(name).size() == 1
&& tmpnode.getJSONObject(name).containsKey(name)
&& tmpnode.getJSONObject(name).get(name).getClass().equals(JSONArray.class)) {
temp.get(name).add(tmpnode.getJSONObject(name).get(name));
} else {
temp.get(name).add(tmpnode.get(name));
}
}
for (String name : temp.keySet()) {
if (temp.get(name).size() == 1) {
jsonnode.put(name, temp.get(name).get(0));
} else {
jsonnode.put(name, temp.get(name));
}
}
}
if ((jsonnode.size() == 1 && jsonnode.containsKey(textsign)) || jsonnode.size() == 0) {
json.put(nodename, text);
} else {
json.put(nodename, jsonnode);
}
}
public static String JsonToXml(String json) {
JSONObject jsonnode = JSONObject.fromObject(json);
Document doc = DocumentHelper.createDocument();
Element root = doc.addElement("root");
convertJsonToXML(jsonnode, root);
if (root.elements().size() == 1) {
doc.setRootElement(root.elements().get(0));
}
StringWriter sw = new StringWriter();
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
try {
XMLWriter xmlWriter = new XMLWriter(sw, format);
xmlWriter.write(doc);
} catch (IOException ex) {
logger.error(ex.getMessage());
} finally {
try {
sw.close();
} catch (IOException ex) {
logger.error(ex.getMessage());
}
}
return sw.toString();
}
@SuppressWarnings("unchecked")
private static void convertJsonToXML(JSONObject jsonnode, Element node) {
Element el;
for (Iterator<String> it = jsonnode.keys(); it.hasNext();) {
String key = it.next();
Object obj = jsonnode.get(key);
if (obj.getClass().equals(JSONObject.class)) {
el = node.addElement(key);
convertJsonToXML((JSONObject) obj, el);
} else if (obj.getClass().equals(JSONArray.class)) {
JSONArray ja = (JSONArray) obj;
convertJsonToXML(key, ja, node);
} else if (key.indexOf(arrtsign) == 0) {
node.addAttribute(key.substring(1), obj.toString());
} else if (textsign.equals(key)) {
node.addText(obj.toString());
} else {
el = node.addElement(key);
el.addText(obj.toString());
}
}
}
private static void convertJsonToXML(String key, JSONArray ja, Element node) {
Element el;
for (int i = 0; i < ja.size(); i++) {
Object obj = ja.get(i);
el = node.addElement(key);
if (obj.getClass().equals(JSONObject.class)) {
convertJsonToXML((JSONObject) obj, el);
} else if (obj.getClass().equals(JSONArray.class)) {
convertJsonToXML(key, (JSONArray) obj, el);
} else if (key.indexOf(arrtsign) == 0) {
node.addAttribute(key.substring(1), obj.toString());
} else if (textsign.equals(key)) {
node.addText(obj.toString());
} else {
el.addText(obj.toString());
}
}
}
}