欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > 【工具类】Java优雅的将XML转为JSON格式、XML转JSON

【工具类】Java优雅的将XML转为JSON格式、XML转JSON

2025/2/24 13:20:41 来源:https://blog.csdn.net/qq_43565087/article/details/141426401  浏览:    关键词:【工具类】Java优雅的将XML转为JSON格式、XML转JSON

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流数据等

3.运行示例

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词