欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java實現(xiàn)XML與JSON的互相轉(zhuǎn)換詳解

 更新時間:2025年03月19日 14:48:50   作者:心的步伐  
這篇文章主要為大家詳細介紹了如何使用Java實現(xiàn)XML與JSON的互相轉(zhuǎn)換,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

1. XML轉(zhuǎn)JSON

1.1 代碼目的

實現(xiàn)xml與json的互相轉(zhuǎn)換,先實現(xiàn)xml -> json, 然后實現(xiàn)json -> xml字符串,最后xml字符串 -> 寫入文件

XML結(jié)構(gòu)時常會轉(zhuǎn)換為JSON數(shù)據(jù)結(jié)構(gòu),感恩開源,有json的開源包幫忙解決問題。

1.2 代碼實現(xiàn)

下面代碼是xml轉(zhuǎn)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轉(zhuǎn)json方法
        JSONObject jsonObject = XML.toJSONObject(read.asXML());
        //設(shè)置縮進轉(zhuǎn)為字符串
        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>

輸出結(jié)果:

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

2. JSON轉(zhuǎn)XML

    //json轉(zhuǎn)換成xml
    public static String jsonToXml(String json){
        //輸入流
        StringReader input = new StringReader(json);
        //輸出流
        StringWriter output = new StringWriter();
        //構(gòu)建配置文件
        JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).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文檔的頂級界面。
                //驗證XML的形式不需要此接口的實例。
                XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
                //創(chuàng)建一個實例使用默認(rèn)的縮進和換行
                writer = new PrettyXMLEventWriter(writer);
                //添加整個流到輸出流,調(diào)用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();
                        }
                     }
            //移除頭部標(biāo)簽
            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轉(zhuǎn)json中輸出的,json轉(zhuǎn)xml的結(jié)果如下:

此時是沒有頭部,在文中被移除!

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

3. JSON轉(zhuǎn)XML并輸出成指定的文件

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

public static void writeXmlToFile(String xmlStr) throws Exception{
        //將xmlstr轉(zhuǎn)為文件形式
        Document document = DocumentHelper.parseText(xmlStr);
        //設(shè)置輸出的格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        //構(gòu)建輸出流
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("newXml.xml"), format);
        //不要轉(zhuǎn)義字符
        xmlWriter.setEscapeText(false);
        //寫入
        xmlWriter.write(document);
        //關(guān)閉流
        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轉(zhuǎn)化成json
        String jsonStr = xmlToJson();
        //將json轉(zhuǎn)換成xml
        String xmlStr = jsonToXml(jsonStr);
        //將json按照響應(yīng)格式寫入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轉(zhuǎn)json方法
        JSONObject jsonObject = XML.toJSONObject(read.asXML());
        //設(shè)置縮進轉(zhuǎn)為字符串
        System.out.println(jsonObject.toString(3));
        return jsonObject.toString(3);
    }

    public static void writeXmlToFile(String xmlStr) throws Exception{
        //將xmlstr轉(zhuǎn)為文件形式
        Document document = DocumentHelper.parseText(xmlStr);
        //設(shè)置輸出的格式
        OutputFormat format = OutputFormat.createPrettyPrint();
        //構(gòu)建輸出流
        XMLWriter xmlWriter = new XMLWriter(new FileOutputStream("G:\\IDEAProjects\\JavaStudy\\Mooc\\src\\main\\resources\\score2.xml"), format);
        //不要轉(zhuǎn)義字符
        xmlWriter.setEscapeText(false);
        //寫入
        xmlWriter.write(document);
        //關(guān)閉流
        xmlWriter.close();
    }


    //json轉(zhuǎn)換成xml
    public static String jsonToXml(String json){
        //輸入流
        StringReader input = new StringReader(json);
        //輸出流
        StringWriter output = new StringWriter();
        //構(gòu)建配置文件
        JsonXMLConfig config = new JsonXMLConfigBuilder().multiplePI(false).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文檔的頂級界面。
                //驗證XML的形式不需要此接口的實例。
                XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
                //創(chuàng)建一個實例使用默認(rèn)的縮進和換行
                writer = new PrettyXMLEventWriter(writer);
                //添加整個流到輸出流,調(diào)用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();
                        }
                     }
            //移除頭部標(biāo)簽
            if (output.toString().length() >= 38) {
                System.out.println(output.toString().substring(39));
                return output.toString().substring(39);
            }
        System.out.println(output);
        return output.toString();
    }
}

到此這篇關(guān)于Java實現(xiàn)XML與JSON的互相轉(zhuǎn)換詳解的文章就介紹到這了,更多相關(guān)Java XML與JSON互轉(zhuǎn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Idea配置超詳細圖文教程(2020.2版本)

    Idea配置超詳細圖文教程(2020.2版本)

    這篇文章主要介紹了Idea配置超詳細圖文教程(2020.2版本),本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-08-08
  • 從零搭建腳手架之集成Spring?Retry實現(xiàn)失敗重試和熔斷器模式(實戰(zhàn)教程)

    從零搭建腳手架之集成Spring?Retry實現(xiàn)失敗重試和熔斷器模式(實戰(zhàn)教程)

    在我們的大多數(shù)項目中,會有一些場景需要重試操作,而不是立即失敗,讓系統(tǒng)更加健壯且不易發(fā)生故障,這篇文章主要介紹了從零搭建開發(fā)腳手架之集成Spring?Retry實現(xiàn)失敗重試和熔斷器模式,需要的朋友可以參考下
    2022-07-07
  • spring中使用@Autowired注解無法注入的情況及解決

    spring中使用@Autowired注解無法注入的情況及解決

    這篇文章主要介紹了spring中使用@Autowired注解無法注入的情況及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • Java利用Request請求如何獲取IP地址對應(yīng)的省份、城市詳解

    Java利用Request請求如何獲取IP地址對應(yīng)的省份、城市詳解

    之前已經(jīng)給大家介紹了關(guān)于Java用Request請求獲取IP地址的相關(guān)內(nèi)容,那么下面這篇文章將給大家進入深入的介紹,關(guān)于Java利用Request請求如何獲取IP地址對應(yīng)省份、城市的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-10-10
  • SpringBoot執(zhí)行定時任務(wù)@Scheduled的方法

    SpringBoot執(zhí)行定時任務(wù)@Scheduled的方法

    這篇文章主要介紹了SpringBoot執(zhí)行定時任務(wù)@Scheduled的方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-07-07
  • vscode 配置java環(huán)境并調(diào)試運行的詳細過程

    vscode 配置java環(huán)境并調(diào)試運行的詳細過程

    這篇文章主要介紹了vscode 配置java環(huán)境并調(diào)試運行的詳細過程,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-05-05
  • Java基礎(chǔ)Map集合詳析

    Java基礎(chǔ)Map集合詳析

    這篇文章主要介紹了Java基礎(chǔ)Map集合詳析,主要通過介紹Map集合的常用方法、Map的獲取方法的一些相關(guān)資料展開內(nèi)容,需要的小伙伴可以參考一下
    2022-04-04
  • Java?詳解分析鏈表的中間節(jié)點

    Java?詳解分析鏈表的中間節(jié)點

    鏈表是基本的數(shù)據(jù)結(jié)構(gòu)之一,面試題中鏈表占很大一部分,可見鏈表操作是非常重要的。本篇文章我們來探究一下如何獲取鏈表的中間節(jié)點
    2022-01-01
  • Spring @Conditional注解從源碼層講解

    Spring @Conditional注解從源碼層講解

    @Conditional是Spring4新提供的注解,它的作用是按照一定的條件進行判斷,滿足條件給容器注冊bean,這篇文章主要介紹了Spring @Conditional注解示例詳細講解,需要的朋友可以參考下
    2023-01-01
  • Spring中的三級緩存與循環(huán)依賴詳解

    Spring中的三級緩存與循環(huán)依賴詳解

    Spring三級緩存是Spring框架中用于解決循環(huán)依賴問題的一種機制,這篇文章主要介紹了Spring三級緩存與循環(huán)依賴的相關(guān)知識,本文給大家介紹的非常詳細,需要的朋友可以參考下
    2024-05-05

最新評論