JAVA /Springboot XML 转JSON 代码端处理
package org.jeecg.modules.system.util;
import org.apache.commons.lang.StringUtils;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import com.alibaba.fastjson.JSONObject;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.testng.annotations.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
/**
* Created by CSDN 桃树-李树.
*/
public class XmlUtils {
public static JSONObject xml2Json(String xmlStr) throws JDOMException, IOException {
if (StringUtils.isEmpty(xmlStr)) {
return null;
}
xmlStr = xmlStr.replaceAll("\\\n", "");
byte[] xml = xmlStr.getBytes("GBK");
JSONObject json = new JSONObject();
InputStream is = new ByteArrayInputStream(xml);
SAXBuilder sb = new SAXBuilder();
Document doc = sb.build(is);
Element root = doc.getRootElement();
json.put(root.getName(), iterateElement(root));
return json;
}
private static JSONObject iterateElement(Element element) {
List<Element> node = element.getChildren();
JSONObject obj = new JSONObject();
List list = null;
for (Element child : node) {
list = new LinkedList();
String text = child.getTextTrim();
if (StringUtils.isBlank(text)) {
if (child.getChildren().size() == 0) {
continue;
}
if (obj.containsKey(child.getName())) {
list = (List) obj.get(child.getName());
}
list.add(iterateElement(child)); //遍历child的子节点
obj.put(child.getName(), list);
} else {
if (obj.containsKey(child.getName())) {
Object value = obj.get(child.getName());
try {
list = (List) value;
} catch (ClassCastException e) {
list.add(value);
}
}
if (child.getChildren().size() == 0) { //child无子节点时直接设置text
obj.put(child.getName(), text);
} else {
list.add(text);
obj.put(child.getName(), list);
}
}
}
return obj;
}
@Test
public void test() throws JDOMException, IOException {
String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
"<stream><abstract>测试机</abstract><chknum></chknum><failAmount>0.00</failAmount><failNum>0</failNum><payAccountNo>88888888888888888</payAccountNo><status>AAAAAAA</status><statusText>交易成功</statusText><succAmount>0.10</succAmount><succNum>1</succNum><list name=\"userDataList\"><row><ID>10001</ID><abstract>测试机</abstract><field1></field1><field2></field2><field3></field3><recAccountName>张某某</recAccountName><recAccountNo>6227000130060638382</recAccountNo><status>AAAAAAA</status><statusText>交易成功</statusText><stt>S2</stt><sttText>交易成功</sttText><tranAmount>0.10</tranAmount></row></list></stream>";
JSONObject json = xml2Json(xml);
String respMsg = json.toJSONString();
System.out.println(respMsg);
}
}
处理为GBK