Java實(shí)現(xiàn)XML與JSON的互相轉(zhuǎn)換詳解
1. XML轉(zhuǎn)JSON
1.1 代碼目的
實(shí)現(xiàn)xml與json的互相轉(zhuǎn)換,先實(shí)現(xiàn)xml -> json, 然后實(shí)現(xiàn)json -> xml字符串,最后xml字符串 -> 寫入文件
XML結(jié)構(gòu)時(shí)常會轉(zhuǎn)換為JSON數(shù)據(jù)結(jié)構(gòu),感恩開源,有json的開源包幫忙解決問題。
1.2 代碼實(shí)現(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è)置縮進(jìn)轉(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事件最頂層的接口,它提供了查看下一個(gè)事件并通過屬性界面返回配置信息的功能。
XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
//這是編寫XML文檔的頂級界面。
//驗(yàn)證XML的形式不需要此接口的實(shí)例。
XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
//創(chuàng)建一個(gè)實(shí)例使用默認(rèn)的縮進(jìn)和換行
writer = new PrettyXMLEventWriter(writer);
//添加整個(gè)流到輸出流,調(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é)果如下:
此時(shí)是沒有頭部,在文中被移除!
<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è)置縮進(jìn)轉(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事件最頂層的接口,它提供了查看下一個(gè)事件并通過屬性界面返回配置信息的功能。
XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
//這是編寫XML文檔的頂級界面。
//驗(yàn)證XML的形式不需要此接口的實(shí)例。
XMLEventWriter writer = XMLOutputFactory.newInstance().createXMLEventWriter(output);
//創(chuàng)建一個(gè)實(shí)例使用默認(rèn)的縮進(jìn)和換行
writer = new PrettyXMLEventWriter(writer);
//添加整個(gè)流到輸出流,調(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實(shí)現(xiàn)XML與JSON的互相轉(zhuǎn)換詳解的文章就介紹到這了,更多相關(guān)Java XML與JSON互轉(zhuǎn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于JSqlparser使用攻略(高效的SQL解析工具)
這篇文章主要介紹了關(guān)于JSqlparser使用攻略(高效的SQL解析工具),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
mybatis項(xiàng)目兼容mybatis-plus問題
這篇文章主要介紹了mybatis項(xiàng)目兼容mybatis-plus問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02
利用SpringDataJPA開啟審計(jì)功能,自動(dòng)保存操作人操作時(shí)間
這篇文章主要介紹了利用SpringDataJPA開啟審計(jì)功能,自動(dòng)保存操作人操作時(shí)間,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
spring boot使用@Async異步注解的實(shí)現(xiàn)原理+源碼
通常我們都是采用多線程的方式來實(shí)現(xiàn)上述業(yè)務(wù)功能,但spring 提供更優(yōu)雅的方式來實(shí)現(xiàn)上述功能,就是@Async 異步注解,在方法上添加@Async,spring就會借助AOP,異步執(zhí)行方法,接下來通過本文給大家介紹spring boot異步注解的相關(guān)知識,一起看看吧2021-06-06
SpringBoot集成H2內(nèi)存數(shù)據(jù)庫的方法
H2是Thomas Mueller提供的一個(gè)開源的、純java實(shí)現(xiàn)的關(guān)系數(shù)據(jù)庫。本文主要介紹了SpringBoot集成H2內(nèi)存數(shù)據(jù)庫,具有一定的參考價(jià)值,感興趣的可以了解一下2021-09-09
IDEA通過git回滾到某個(gè)提交節(jié)點(diǎn)或某個(gè)版本的操作方法
這篇文章主要介紹了IDEA通過git回滾到某個(gè)提交節(jié)點(diǎn)或某個(gè)版本的方法,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07

