​

1.pom依赖


<dependency>
<groupId>org.jdom</groupId>
<artifactId>jdom</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.39</version>
</dependency>


2.代码


1 public class Xml2JsonUtil { 
2
3 /**
4 * 转换一个xml格式的字符串到json格式
5 *
6 * @param xml
7 * xml格式的字符串
8 * @return 成功返回json 格式的字符串;失败反回null
9 */
10 public static String xml2JSON(String xml) {
11 JSONObject obj = new JSONObject();
12 try {
13 InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
14 SAXBuilder sb = new SAXBuilder();
15 Document doc = sb.build(is);
16 Element root = doc.getRootElement();
17 obj.put(root.getName(), iterateElement(root));
18 return obj.toString();
19 } catch (Exception e) {
20 e.printStackTrace();
21 return null;
22 }
23 }
24
25 /**
26 * 转换一个xml格式的字符串到json格式
27 *
28 * @param file
29 * java.io.File实例是一个有效的xml文件
30 * @return 成功反回json 格式的字符串;失败反回null
31 */
32 public static String xml2JSON(File file) {
33 JSONObject obj = new JSONObject();
34 try {
35 SAXBuilder sb = new SAXBuilder();
36 Document doc = sb.build(file);
37 Element root = doc.getRootElement();
38 obj.put(root.getName(), iterateElement(root));
39 return obj.toString();
40 } catch (Exception e) {
41 e.printStackTrace();
42 return null;
43 }
44 }
45
46 /**
47 * 一个迭代方法
48 *
49 * @param element
50 * : org.jdom.Element
51 * @return java.util.Map 实例
52 */
53 @SuppressWarnings({ "rawtypes", "unchecked" })
54 private static Map iterateElement(Element element) {
55 List jiedian = element.getChildren();
56 Element et = null;
57 Map obj = new HashMap();
58 List list = null;
59 for (int i = 0; i < jiedian.size(); i++) {
60 list = new LinkedList();
61 et = (Element) jiedian.get(i);
62 if (et.getTextTrim().equals("")) {
63 if (et.getChildren().size() == 0)
64 continue;
65 if (obj.containsKey(et.getName())) {
66 list = (List) obj.get(et.getName());
67 }
68 list.add(iterateElement(et));
69 obj.put(et.getName(), list);
70 } else {
71 if (obj.containsKey(et.getName())) {
72 list = (List) obj.get(et.getName());
73 }
74 list.add(et.getTextTrim());
75 obj.put(et.getName(), list);
76 }
77 }
78 return obj;
79 }
80
81 // 测试
82 public static void main(String[] args) {
83 String xml = "<xml><version><![CDATA[2.0]]></version><charset><![CDATA[UTF-8]]></charset><status><![CDATA[400]]></status><message><![CDATA[Require POST method]]></message></xml>";
84 System.out.println(Xml2JsonUtil.xml2JSON(xml));
85 }
86 }


3.运行结果(手动格式化了的)


{
"xml":{
"charset":[
"UTF-8"
],
"message":[
"Require POST method"
],
"version":[
"2.0"
],
"status":[
"400"
]
}
}