Java工具类:将xml转为Json
一、场景
在对接第三方接口时,由于接口返回的并不是常见的Json,而是XML,所以需要将XML转为Json,方便后续处理
二、工具类
package com.xxx.util;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.ByteArrayInputStream;
import java.util.List;
/**
* @author hcs
*
* @date 2024/1/19 10:55
*/
public class XmlConverToJsonUtil {
/**
* 将xml转为json
*
* @param xml
* @return
*/
public static com.alibaba.fastjson.JSONObject xmlConversionToJSON(String xml) {
System.out.println("要转换的XML:\n" + xml);
if (StringUtils.isBlank(xml)) {
return null;
}
Document document = null;
Element root = null;
List<Element> elementList = null;
List<Element> parantList = null;
List<Element> childList = null;
SAXReader reader = null;
try {
reader = new SAXReader();
try {
document = reader.read(new ByteArrayInputStream(xml.getBytes(Constant.default_encoding)));
} catch (Exception e) {
e.printStackTrace();
return null;
}
root = document.getRootElement();
elementList = root.elements();
com.alibaba.fastjson.JSONObject map = new com.alibaba.fastjson.JSONObject();
for (Element e : elementList) {
String strName = e.getName();
//map.put(strName, e.getText());
map.put(strName, getElementValue(e, new com.alibaba.fastjson.JSONObject()));
}
return map;
} catch (Exception e) {
e.printStackTrace();
} finally {
document = null;
root = null;
if (elementList != null) {
elementList.clear();
}
elementList = null;
if (parantList != null) {
parantList.clear();
}
parantList = null;
if (childList != null) {
childList.clear();
}
childList = null;
reader = null;
}
return null;
}
/**
* 遍历,获取元素值
*
* @param e
* @param map
* @return
*/
private static Object getElementValue(Element e, com.alibaba.fastjson.JSONObject map){
List<Element> elements = e.elements();
if (elements == null || elements.size() < 1) {
return e.getText();
} else {
for (Element element : elements) {
List elements2 = element.elements();
if (elements2 == null || elements2.size() < 1) {
map.put(element.getName(), element.getText());
} else {
map.put(element.getName(), getElementValue(element, new com.alibaba.fastjson.JSONObject()));
}
}
return map;
}
}
}
三、测试类
package com.xxx;
import com.xxx.util.XmlConverToJsonUtil;
public class XmlTest {
public static void main(String[] args) {
String xmlStr = "<USER_INFO>\n" +
"\t<NAME>张三</NAME>\n" +
"\t<COMPANY>XXX股份有限公司</COMPANY>\n" +
"\t<AUDIT_STATUS>3</AUDIT_STATUS>\n" +
"\t<REGISTRANT>张三</REGISTRANT>\n" +
"\t<PHONE_NUMBER>12345678901</PHONE_NUMBER>\n" +
"\t<MAILBOX></MAILBOX>\n" +
"\t<USER_GUID>eee-ddd-ccc-bbb-aaa</USER_GUID>\n" +
"\t<SOURCE_APP_CODE>AAA</SOURCE_APP_CODE\n" +
"\t><EXPERT_GRADE></EXPERT_GRADE>\n" +
"</USER_INFO>";
System.out.println("\n转为JSON对象:\n" + XmlConverToJsonUtil.xmlConversionToJSON(xmlStr));
}
}
四、测试结果
原文地址:https://blog.csdn.net/weixin_52116015/article/details/135692406
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!