<dependency>
<groupId>maven</groupId>
<artifactId>dom4j</artifactId>
<version>1.7-20060614</version>
</dependency>
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import java.util.List;
/**
* @project
* @Description XML轉json對象工具類
* @Author songwp
* @Date 2022/9/20 9:54
* @Version 1.0.0
**/
public class XmltoJsonUtil {
/**
* 將xml轉換為json對象
*/
public static JSONObject xmlToJson(String xml) throws DocumentException {
JSONObject jsonObject = new JSONObject();
Document document = DocumentHelper.parseText(xml);
//獲取根節點元素對象
Element root = document.getRootElement();
iterateNodes(root, jsonObject);
return jsonObject;
}
/**
* 遍曆元素
* @param node
* @param json
*/
private static void iterateNodes(Element node, JSONObject json) {
//獲取當前元素名稱
String nodeName = node.getName();
//判斷已遍歷的JSON中是否已經有了該元素的名稱
if(json.containsKey(nodeName)){
//該元素在同級下有多個
Object Object = json.get(nodeName);
JSONArray array = null;
if(Object instanceof JSONArray){
array = (JSONArray) Object;
}else {
array = new JSONArray();
array.add(Object);
}
//獲取該元素下所有子元素
List<Element> listElement = node.elements();
if(listElement.isEmpty()){
//該元素無子元素,獲取元素的值
String nodeValue = node.getTextTrim();
array.add(nodeValue);
json.put(nodeName, array);
return ;
}
//有子元素
JSONObject newJson = new JSONObject();
//遍歷所有子元素
for(Element e:listElement){
//遞歸
iterateNodes(e,newJson);
}
array.add(newJson);
json.put(nodeName, array);
return ;
}
//該元素同級下第一次遍歷
//獲取該元素下所有子元素
List<Element> listElement = node.elements();
if(listElement.isEmpty()){
//該元素無子元素,獲取元素的值
String nodeValue = node.getTextTrim();
json.put(nodeName, nodeValue);
return ;
}
//有子節點,新建一個JSONObject來存儲該節點下子節點的值
JSONObject object = new JSONObject();
for(Element e:listElement){
//遞歸
iterateNodes(e,object);
}
json.put(nodeName, object);
return ;
}
public static void main(String[] args) {
try {
JSONObject object = XmltoJsonUtil.xmlToJson("<auibinsurancecallback><policyinfo><transtype>TKTS</transtype><eticketno>xxx</eticketno><flightnumber>xxx</flightnumber><flightdate>2019-10-16</flightdate><operatetime>2019-10-16 17:20:00</operatetime><insureno>1910161720056066735</insureno><agreeno>102160199</agreeno><policyno></policyno><policyurl><!--[CDATA[]]--></policyurl></policyinfo><returninfo><serialnumber>2019103015284949545354</serialnumber><retruncode>0</retruncode><errormessage><!--[CDATA[xxx]]--></errormessage></returninfo></auibinsurancecallback>");
System.out.println(object);
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
{
"auibinsurancecallback":{
"returninfo":{
"errormessage":"",
"retruncode":"0",
"serialnumber":"2019103015284949545354"
},
"policyinfo":{
"policyurl":"",
"operatetime":"2019-10-16 17:20:00",
"transtype":"TKTS",
"flightdate":"2019-10-16",
"insureno":"1910161720056066735",
"flightnumber":"xxx",
"agreeno":"102160199",
"policyno":"",
"eticketno":"xxx"
}
}
}