Java实现XML与JSON的互相转换详解

2025-03-20 01:50

本文主要是介绍Java实现XML与JSON的互相转换详解,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《Java实现XML与JSON的互相转换详解》这篇文章主要为大家详细介绍了如何使用Java实现XML与JSON的互相转换,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下...

1. XML转JSON

1.1 代码目的

实现xml与json的互相转换,先实现xml -> json, 然后实现json -> xml字符串,最后xml字符串 -> 写入文件

XML结构时常会转换为JSON数据结构,感恩开源,有json的开源包帮忙解决问题。

1.2 代码实现

下面代码是xml转json的快速方法

public static String xmlToJson() throws Exception{
        //使用DOM4j
        SAXReader saxReader = new SAXReader();
        //读取文件
        Document read = saxReader.read("G:\\IDEAProjects\\JavaStudy\\Mooc\\src\\main\\resources\\score.xml");
        //使用json的xml转json方法
        JSONObject jsonObject = XML.toJSONObject(read.asXML());
        //设置缩进转为字符串
        System.out.println(jsonObject.toString(3));
        return jsonObject.toString(3);
    }

测试xml文件如下

<?xml version='1.0' encoding='UTF-8'?>
<student>
    <name>Tom</name>
    <subject>math</subject>
    <score>80</score>
</student>

输出结果:

{"student": 
 {
   "score": 80,
   "subject": "math",
   "name": "Tom"
 }
}

2. JSON转XML

    //json转换成xml
    public static String jsonToXml(String json){
        //输入流
        StringReader input = new StringReader(json);
        //输出流
        StringWriter output = new StringWriter();
        //构建配置文件
        JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(falsphpe).repairingNamespaces(false).build();
        try {
                //xml事件读
                //  This is the top level interface for parsing XML Events.  It provides
                //  the ability to peek at the next event and returns configuration
                //  information through the property interface.
                // 这是最解析XML事件最顶层的接口,它提供了查看下一个事件并通过属性界面返回配置信息的功能。
                XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
                //这是编写XML文档的顶级界面。
js                //验证XML的形式不需要此接口的实例。
                XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
                //创建一个实例使用默认的缩进和换行
                writer = new PrettyXMLEventWriter(writer);
                //添加整个流到输出流,调用next方法,知道hasnext返回false
                writer.add(reader);
                reader.close();
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
      python              try {
                            output.close();
                            input.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                     }
            //移除头部标签
            if (output.toString().length() >= 38) {
                System.out.println(output.toString().substring(39));
                return output.toString().substring(39);
            }
        System.out.println(output);
        return output.toString();
    }

传入的json字符串即上xml转json中输出的,json转xml的结果如下:

此时是没有头部,在文中被移除!

<student>
    <score>80</score>
    <subject>math</subject>
    <name>Tom</name>
</student>

3. JSON转XML并输出成指定的文件

传入xml字符串,利用DOM4J工具即可输出到指定的文件

public static void writeXmlToFile(String xmlStr) throws Exception{
        //将xmlstr转为文件形式
        Document document = DocumentHelper.parseText(xmlStr);
        //设置输出的格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        //构建输出流
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("newXml.xml"), format);
        //不要转义字符
        xmlWriter.setEscapeText(false);
        //写入
        xmlWriter.write(document);
        //关闭流
        xmlWriter.close();
    }

4. 主要的pom.xml配置如下

如下的依赖就足够了

	<dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20171018</version>
        </dependency>
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>de.odysseus.staxon</groupId>
            <artifactId>staxon</artifactId>
            <version>1.3</version>
        </dependency>

5. 整体代码

public class Main {
    public static void main(String[] args)throws Exception {
        //将xml转化成json
        String jsonStr = xmlToJson();
        //将json转换成xml
        String xmlStr = jsonToXml(jsonStr);
        //将json按照响应格式写入score2.xml
        writeXmlToFile(xmlStr);

    }

    public static String xmlToJson() throws Exception{
        //使用DOM4j
        SAXReader saxReader = new SAXReader();
        //读取文件
        Document read = saxReader.read("G:\\IDEAProjects\\JavaStudy\\Mooc\\src\\main\\resources\\score.xml");
        //使用json的xml转json方法
        JSONObject jsonObject = XML.toJSONObject(read.asXML());
        //设置缩进转为字符串
        System.out.println(jsonObject.toString(3));
        return jsonObject.toString(3);
    }

    public static void writeXmlToFile(String xmlStr) throws Exception{
        //将xmlstr转为文件形式
        Document document = DocumentHelper.parseText(xmlStr);
        //设置输出的格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        //构建输出流
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("G:\\IDEAProjects\\JavaStudy\\Mooc\\src\\main\\resources\\score2.xml"), format);
        //不要转义字符
        xmlWriter.setEscapeText(false);
        //写入
        xmlWriter.write(document);
        //关闭流
        xmlWriter.close();
    }


    //json转换成xml
    public static String jsonToXml(String json){
        //输入流
        StringReader input = new StringReadewww.chinasem.cnr(json);
        //输出流
        StringWriter output = new StringWriter();
        //构建配置文件
        JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).repairingNamespaces(false).build();
        try {
               China编程 //xml事件读
                //  This is the top level interface for parsing XML Events.  It provides
                //  the ability to peek at the next event and returns configuration
                //  information through the property interface.
                // 这是最解析XML事件最顶层的接口,它提供了查看下一个事件并通过属性界面返回配置信息的功能。
                XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
                //这是编写XML文档的顶级界面。
                //验证XML的形式不需要此接口的实例。
                XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
                //创建一个实例使用默认的缩进和换行
                writer = new PrettyXMLEventWriter(writer);
                //添加整个流到输出流,调用next方法,知道hasnext返回false
                writer.add(reader);
                reader.close();
                writer.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                    try {
                            output.close();
                            input.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                     }
            //移除头部标签
            if (output.toString().length() >= 38) {
                System.out.println(output.toString().substring(39));
                return output.toString().substring(39);
            }
        System.out.println(output);
        return output.toString();
    }
}

到此这篇关于Java实现XML与JSON的互相转换详解的文章就介绍到这了,更多相关Java XML与JSON互转内容请搜索China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程China编程(www.chinasem.cn)!

这篇关于Java实现XML与JSON的互相转换详解的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1153845

相关文章

利用Python实现添加或读取Excel公式

《利用Python实现添加或读取Excel公式》Excel公式是数据处理的核心工具,从简单的加减运算到复杂的逻辑判断,掌握基础语法是高效工作的起点,下面我们就来看看如何使用Python进行Excel公... 目录python Excel 库安装Python 在 Excel 中添加公式/函数Python 读取

Spring AI ectorStore的使用流程

《SpringAIectorStore的使用流程》SpringAI中的VectorStore是一种用于存储和检索高维向量数据的数据库或存储解决方案,它在AI应用中发挥着至关重要的作用,本文给大家介... 目录一、VectorStore的基本概念二、VectorStore的核心接口三、VectorStore的

Jackson库进行JSON 序列化时遇到了无限递归(Infinite Recursion)的问题及解决方案

《Jackson库进行JSON序列化时遇到了无限递归(InfiniteRecursion)的问题及解决方案》使用Jackson库进行JSON序列化时遇到了无限递归(InfiniteRecursi... 目录解决方案‌1. 使用 @jsonIgnore 忽略一个方向的引用2. 使用 @JsonManagedR

Python实现合并与拆分多个PDF文档中的指定页

《Python实现合并与拆分多个PDF文档中的指定页》这篇文章主要为大家详细介绍了如何使用Python实现将多个PDF文档中的指定页合并生成新的PDF以及拆分PDF,感兴趣的小伙伴可以参考一下... 安装所需要的库pip install PyPDF2 -i https://pypi.tuna.tsingh

最新Spring Security实战教程之Spring Security安全框架指南

《最新SpringSecurity实战教程之SpringSecurity安全框架指南》SpringSecurity是Spring生态系统中的核心组件,提供认证、授权和防护机制,以保护应用免受各种安... 目录前言什么是Spring Security?同类框架对比Spring Security典型应用场景传统

最新Spring Security实战教程之表单登录定制到处理逻辑的深度改造(最新推荐)

《最新SpringSecurity实战教程之表单登录定制到处理逻辑的深度改造(最新推荐)》本章节介绍了如何通过SpringSecurity实现从配置自定义登录页面、表单登录处理逻辑的配置,并简单模拟... 目录前言改造准备开始登录页改造自定义用户名密码登陆成功失败跳转问题自定义登出前后端分离适配方案结语前言

python中time模块的常用方法及应用详解

《python中time模块的常用方法及应用详解》在Python开发中,时间处理是绕不开的刚需场景,从性能计时到定时任务,从日志记录到数据同步,时间模块始终是开发者最得力的工具之一,本文将通过真实案例... 目录一、时间基石:time.time()典型场景:程序性能分析进阶技巧:结合上下文管理器实现自动计时

基于Python和Tkinter实现高考倒计时功能

《基于Python和Tkinter实现高考倒计时功能》随着高考的临近,每个考生都在紧锣密鼓地复习,这时候,一款实用的倒计时软件能有效帮助你规划剩余时间,提醒你不要浪费每一分每一秒,今天,我们来聊聊一款... 目录一、软件概述:二、功能亮点:1. 高考倒计时2. 添加目标倒计时3. 励志语句4. 透明度调节与

SpringSecurity 认证、注销、权限控制功能(注销、记住密码、自定义登入页)

《SpringSecurity认证、注销、权限控制功能(注销、记住密码、自定义登入页)》SpringSecurity是一个强大的Java框架,用于保护应用程序的安全性,它提供了一套全面的安全解决方案... 目录简介认识Spring Security“认证”(Authentication)“授权” (Auth

Python实现PDF与多种图片格式之间互转(PNG, JPG, BMP, EMF, SVG)

《Python实现PDF与多种图片格式之间互转(PNG,JPG,BMP,EMF,SVG)》PDF和图片是我们日常生活和工作中常用的文件格式,有时候,我们可能需要将PDF和图片进行格式互转来满足... 目录一、介绍二、安装python库三、Python实现多种图片格式转PDF1、单张图片转换为PDF2、多张图