柚子快報(bào)激活碼778899分享:JAVA中將XML轉(zhuǎn)JSON
柚子快報(bào)激活碼778899分享:JAVA中將XML轉(zhuǎn)JSON
?
整理了下網(wǎng)上能找到的常見(jiàn)兩種xml->json的方式,主要是使用json-lib包或者org.json包進(jìn)行轉(zhuǎn)換最后面是現(xiàn)成的工具類(lèi)
壹、使用json-lib方式引入依賴:
貳、使用org.json引入依賴
直接引入org.json包
或者引入hutool的包(推薦)
叁、現(xiàn)成工具類(lèi)
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import net.sf.json.JSON;
import net.sf.json.xml.XMLSerializer;
import org.json.XML;
/**
* @ClassName ConvertXMLtoJSON
* @Description 使用xml字符串轉(zhuǎn)json的三種
* @Date 2023/11/22 10:32
* @Version 1.0
*/
public class ConvertXMLtoJSON {
/** 方式--壹
* 依賴json-lib實(shí)現(xiàn)轉(zhuǎn)換
* @param xmlStr
* @return
*/
public static String xmlToJSON1(String xmlStr){
創(chuàng)建 XMLSerializer對(duì)象
XMLSerializer xmlSerializer = new XMLSerializer();
//將xml轉(zhuǎn)為json(注:如果是元素的屬性,會(huì)在json里的key前加一個(gè)@標(biāo)識(shí))
JSON readJSON = xmlSerializer.read(xmlStr);
//輸出json內(nèi)容
System.out.println(readJSON.toString());
return readJSON.toString();
}
/**
* 方式--貳
* 使用hutool工具包中的工具轉(zhuǎn)化
* @param xmlStr
* @return
*/
public static String xmlToJSON2(String xmlStr){
//這個(gè)方法轉(zhuǎn)換的XML值不全為字符串
JSONObject jsonObject = JSONUtil.xmlToJson(xmlStr);
System.out.println(jsonObject.toString());
//設(shè)置xml的值都以String類(lèi)型顯示
JSONObject jsonObject1 = cn.hutool.json.XML.toJSONObject(xmlStr, true);
System.out.println(jsonObject1.toString());
return jsonObject.toString();
}
/**
* 方式--叁
* 使用org.json中的工具,與hutool的源碼是一樣的
* @param xmlStr
* @return
*/
public static String xmlToJSON3(String xmlStr){
org.json.JSONObject jsonObject1 = XML.toJSONObject(xmlStr);
org.json.JSONObject jsonObject2 = XML.toJSONObject(xmlStr,true);
System.out.println(jsonObject1.toString());
System.out.println(jsonObject2.toString());
return jsonObject2.toString();
}
}
肆、測(cè)試與對(duì)比
public class Demo22 {
public static void main(String[] args) {
String xmlStr="
System.out.println("方式1:"+ ConvertXMLtoJSON.xmlToJSON1(xmlStr));
System.out.println("方式2:"+ ConvertXMLtoJSON.xmlToJSON2(xmlStr));
System.out.println("方式3:"+ ConvertXMLtoJSON.xmlToJSON3(xmlStr));
}
}
原xml數(shù)據(jù)(圖一)、json-lib生成的json(圖二)、org.json生成的json(圖三)
json-lib生成的json字段是按照xml字段順序,但去掉了最外層的標(biāo)簽?;org.json解析的json包含所有的標(biāo)簽,包含最外層的,但沒(méi)有標(biāo)簽順序是亂的
柚子快報(bào)激活碼778899分享:JAVA中將XML轉(zhuǎn)JSON
參考文章
本文內(nèi)容根據(jù)網(wǎng)絡(luò)資料整理,出于傳遞更多信息之目的,不代表金鑰匙跨境贊同其觀點(diǎn)和立場(chǎng)。
轉(zhuǎn)載請(qǐng)注明,如有侵權(quán),聯(lián)系刪除。