导入依赖
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
工具类
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.*;
import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.List;
import java.util.logging.Logger;
/**
* xml转换json工具类
* @Author: LiuYong
* @Date:2019/12/11 10:00
* @Description: TODO xml转换json工具类
*/
public class XmlToJsonUtils {
private static Logger logger = Logger.getLogger(XmlToJsonUtils.class.getName());
public static void main(String[] args) throws Exception {
String xml ="<xml>\n" +
"<appid>wx2421b1c4370ec43b</appid>\n" +
"<attach><![CDATA[att1]]></attach>\n" +
"<body><![CDATA[JSAPI支付测试]]></body>\n" +
"<device_info>1000</device_info>\n" +
"<mch_id>10000100</mch_id>\n" +
"<nonce_str>b927722419c52622651a871d1d9ed8b2</nonce_str>\n" +
"<notify_url>http://wxpay.weixin.qq.com/pub_v2/pay/notify.php</notify_url>\n" +
"<out_trade_no>1405713376</out_trade_no>\n" +
"<spbill_create_ip>127.0.0.1</spbill_create_ip>\n" +
"<total_fee>1</total_fee>\n" +
"<trade_type>JSAPI</trade_type>\n" +
"<sign><![CDATA[3CA89B5870F944736C657979192E1CF4]]></sign>\n" +
"</xml>";
String s = xmlToJson(xml);
System.out.println(s);
JSONObject jsonObject = xml2Json(xml);
System.out.println(jsonObject);
}
/**
* xml字符串转json字符串
* @Author LiuYong
* @Date 2019/12/11 10:06
* @Description TODO
* @param xml
* @return String
**/
public static String xmlToJson(String xml) {
Document doc;
try {
doc = DocumentHelper.parseText(xml);
JSONObject json = new JSONObject();
dom4j2Json(doc.getRootElement(), json);
return json.toJSONString();
} catch (DocumentException e) {
logger.info("数据解析失败");
}
return null;
}
/**
* 根据xml文件路径转换json字符串
* @Author LiuYong
* @Date 2019/12/11 10:06
* @Description TODO
* @param path
* @return String
**/
public static String readFile(String path) throws Exception {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
FileChannel fc = fis.getChannel();
ByteBuffer bb = ByteBuffer.allocate(new Long(file.length()).intValue());
/**fc向buffer中读入数据*/
fc.read(bb);
bb.flip();
String str = new String(bb.array(), "UTF8");
fc.close();
fis.close();
return str;
}
/**
* xml转json
*
* @param xmlStr
* @return
* @throws DocumentException
*/
public static JSONObject xml2Json(String xmlStr) throws DocumentException {
Document doc = DocumentHelper.parseText(xmlStr);
JSONObject json = new JSONObject();
dom4j2Json(doc.getRootElement(), json);
return json;
}
/**
* xml转json
* @Author LiuYong
* @Date 2019/12/11 10:07
* @Description TODO
* @param element
* @param json 外部接收json对象
**/
public static void dom4j2Json(Element element, JSONObject json) {
/**如果是属性*/
for (Object o : element.attributes()) {
Attribute attr = (Attribute) o;
if (!isEmpty(attr.getValue())) {
json.put("@" + attr.getName(), attr.getValue());
}
}
List<Element> chdEl = element.elements();
/**如果没有子元素,只有一个值*/
if (chdEl.isEmpty() && !isEmpty(element.getText())) {
json.put(element.getName(), element.getText());
}
/**有子元素*/
for (Element e : chdEl) {
/**子元素存在子元素*/
if (!e.elements().isEmpty()) {
JSONObject chdjson = new JSONObject();
dom4j2Json(e, chdjson);
Object o = json.get(e.getName());
if (o != null) {
JSONArray jsona = null;
/**如果此元素已存在,则转为jsonArray*/
if (o instanceof JSONObject) {
JSONObject jsono = (JSONObject) o;
json.remove(e.getName());
jsona = new JSONArray();
jsona.add(jsono);
jsona.add(chdjson);
}
if (o instanceof JSONArray) {
jsona = (JSONArray) o;
jsona.add(chdjson);
}
json.put(e.getName(), jsona);
} else {
if (!chdjson.isEmpty()) {
json.put(e.getName(), chdjson);
}
}
} else {
/**子元素没有子元素*/
for (Object o : element.attributes()) {
Attribute attr = (Attribute) o;
if (!isEmpty(attr.getValue())) {
json.put("@" + attr.getName(), attr.getValue());
}
}
if (!e.getText().isEmpty()) {
json.put(e.getName(), e.getText());
}
}
}
}
/**
* 是否为null
* @Author LiuYong
* @Date 2019/12/11 10:28
* @Description TODO
* @param
* @return
**/
public static boolean isEmpty(String str) {
if (str == null || str.trim().isEmpty() || str.equals("null")) {
return true;
}
return false;
}
}
评论 (0)