java實現Xml與json之間的相互轉換操作示例
本文實例講述了java實現Xml與json之間的相互轉換操作。分享給大家供大家參考,具體如下:
旁白:
最近關于xml與json之間的轉換都搞蒙了,這里寫一個demo,以后備用。
正題:
project格式是:
jar包是一個一個檢出來的,還算干凈了。
代碼:
工具類:
package exercise.xml; import net.sf.json.JSON; import net.sf.json.JSONSerializer; import net.sf.json.xml.XMLSerializer; import org.jdom.Document; public class XmlExercise { /** * 將xml字符串<STRONG>轉換</STRONG>為JSON字符串 * * @param xmlString * xml字符串 * @return JSON<STRONG>對象</STRONG> */ public static String xml2json(String xmlString) { XMLSerializer xmlSerializer = new XMLSerializer(); JSON json = xmlSerializer.read(xmlString); return json.toString(1); } /** * 將xmlDocument<STRONG>轉換</STRONG>為JSON<STRONG>對象</STRONG> * * @param xmlDocument * XML Document * @return JSON<STRONG>對象</STRONG> */ public static String xml2json(Document xmlDocument) { return xml2json(xmlDocument.toString()); } /** * JSON(數組)字符串<STRONG>轉換</STRONG>成XML字符串 * * @param jsonString * @return */ public static String json2xml(String jsonString) { XMLSerializer xmlSerializer = new XMLSerializer(); return xmlSerializer.write(JSONSerializer.toJSON(jsonString)); // return xmlSerializer.write(JSONArray.fromObject(jsonString));//這種方式只支持JSON數組 } }
測試類:
package exercise.xml; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class XmlTest extends XmlExercise { public static void main(String[] args) { JSONObject jsonObject = new JSONObject(); jsonObject.put("username", "horizon"); JSONArray jsonArray = new JSONArray(); JSONObject dataJson = new JSONObject(); jsonArray.add(jsonObject); //jsonArray.add(jsonObject); dataJson.put("data", jsonArray); System.out.println(dataJson.toString()); String xml = json2xml(dataJson.toString()); System.out.println("xml:" + xml); String str = xml2json(xml); System.out.println("to_json" + str); } }
PS:這里再為大家提供幾款相關在線工具供大家參考使用:
在線JSON代碼檢驗、檢驗、美化、格式化工具:
http://tools.jb51.net/code/json
在線XML/JSON互相轉換工具:
http://tools.jb51.net/code/xmljson
在線格式化XML/在線壓縮XML:
http://tools.jb51.net/code/xmlformat
XML在線壓縮/格式化工具:
http://tools.jb51.net/code/xml_format_compress
XML代碼在線格式化美化工具:
http://tools.jb51.net/code/xmlcodeformat
更多關于java算法相關內容感興趣的讀者可查看本站專題:《Java操作json格式數據技巧總結》、《Java數據結構與算法教程》、《Java操作DOM節(jié)點技巧總結》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。
相關文章
Spring Boot Starters簡介及其優(yōu)劣勢
在這篇文章中,我們將向你介紹Spring Boot Starters,并將討論Spring Boot Starters的優(yōu)點和優(yōu)勢,感興趣的朋友跟隨腳本之家小編一起學習吧2018-05-05SpringSecurity HttpSecurity 類處理流程分析
SpringSecurity在SSM項目中使用基于配置文件,通過XML標簽定義認證信息,HttpSecurity在SpringBoot中通過代碼配置實現與XML相同功能,詳細介紹了HttpSecurity的類結構、處理過程及其與SecurityBuilder的關系,感興趣的朋友一起看看吧2024-09-09