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í)常會(huì)轉(zhuǎn)換為JSON數(shù)據(jù)結(jié)構(gòu),感恩開源,有json的開源包幫忙解決問(wèn)題。
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);
}
測(cè)試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è)事件并通過(guò)屬性界面返回配置信息的功能。
XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
//這是編寫XML文檔的頂級(jí)界面。
//驗(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í)是沒(méi)有頭部,在文中被移除!
<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è)事件并通過(guò)屬性界面返回配置信息的功能。
XMLEventReader reader = new JsonXMLInputFactory(config).createXMLEventReader(input);
//這是編寫XML文檔的頂級(jí)界面。
//驗(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
從零搭建腳手架之集成Spring?Retry實(shí)現(xiàn)失敗重試和熔斷器模式(實(shí)戰(zhàn)教程)
在我們的大多數(shù)項(xiàng)目中,會(huì)有一些場(chǎng)景需要重試操作,而不是立即失敗,讓系統(tǒng)更加健壯且不易發(fā)生故障,這篇文章主要介紹了從零搭建開發(fā)腳手架之集成Spring?Retry實(shí)現(xiàn)失敗重試和熔斷器模式,需要的朋友可以參考下2022-07-07
spring中使用@Autowired注解無(wú)法注入的情況及解決
這篇文章主要介紹了spring中使用@Autowired注解無(wú)法注入的情況及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
Java利用Request請(qǐng)求如何獲取IP地址對(duì)應(yīng)的省份、城市詳解
之前已經(jīng)給大家介紹了關(guān)于Java用Request請(qǐng)求獲取IP地址的相關(guān)內(nèi)容,那么下面這篇文章將給大家進(jìn)入深入的介紹,關(guān)于Java利用Request請(qǐng)求如何獲取IP地址對(duì)應(yīng)省份、城市的相關(guān)資料,需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-10-10
SpringBoot執(zhí)行定時(shí)任務(wù)@Scheduled的方法
這篇文章主要介紹了SpringBoot執(zhí)行定時(shí)任務(wù)@Scheduled的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
vscode 配置java環(huán)境并調(diào)試運(yùn)行的詳細(xì)過(guò)程
這篇文章主要介紹了vscode 配置java環(huán)境并調(diào)試運(yùn)行的詳細(xì)過(guò)程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-05-05

