Java优雅的将XML转为JSON格式、XML转JSON
- 1. 导入依赖
- 1.1 Maven使用
- 1.2 Gradle使用
- 2. 代码编写
- 3.运行示例
1. 导入依赖
1.1 Maven使用
<dependency><groupId>org.dom4j</groupId><artifactId>dom4j</artifactId><version>2.1.3</version></dependency><dependency><groupId>org.json</groupId><artifactId>json</artifactId><version>20210307</version></dependency>
1.2 Gradle使用
dependencies {implementation("org.dom4j:dom4j:2.1.3")implementation("org.json:json:20210307")
}
2. 代码编写
package com.xcc.utils;import com.xcc.pojo.vo.invoice.EInvoice;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;public class XmlToJsonUtils {public static JSONObject convertToJSON(String xml) throws DocumentException, JSONException {Document document = new SAXReader().read(xml);return parseDocument(document.getRootElement());}private static JSONObject parseDocument(org.dom4j.Element element) throws JSONException {JSONObject json = new JSONObject();Iterator children = element.elementIterator();while (children.hasNext()) {org.dom4j.Element child = (org.dom4j.Element) children.next();if (child.isTextOnly()) {json.put(child.getName(), child.getText());} else {JSONObject childJson = parseDocument(child);if (json.has(child.getName())) {Object existingObject = json.get(child.getName());if (existingObject instanceof JSONObject) {json.accumulate(child.getName(), childJson);} else if (existingObject instanceof org.json.JSONArray) {((org.json.JSONArray) existingObject).put(childJson);}} else {json.put(child.getName(), childJson);}}}return json;}public static void main(String[] args) throws Exception {JSONObject json = convertToJSON("https://csdn.net/xxx.xml");System.out.println(json.toString(2)); // 2 is the indent factor}
}
注:可以根据不同的业务场景来进行选择 提供URL 直接读取和File文件及InputStream流数据等