標籤:
依賴的包:
json-lib-2.4-jdk15.jar
ezmorph-1.0.6.jar
xom-1.2.1.jar
commons-lang-2.1.jar
commons-io-1.3.2.jar
jaxen-1.1.jar
輸入xml檔案,輸出JSON對象
Java代碼
- package com.cash.util;
-
- import java.io.IOException;
- import java.io.InputStream;
-
- import org.apache.commons.io.IOUtils;
- import net.sf.json.JSON;
- import net.sf.json.xml.XMLSerializer;
-
- public class Test {
- public static void ConvertXMLtoJSON() {
- InputStream is = ConvertXMLtoJSON.class.getResourceAsStream("sample.xml");
- String xml;
- try {
- xml = IOUtils.toString(is);
- System.out.println(xml);
- XMLSerializer xmlSerializer = new XMLSerializer();
- JSON json = xmlSerializer.read(xml);
- System.out.println(json.toString(1));
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- public static void main(String[] args) {
- ConvertXMLtoJSON();
- }
- }
Java代碼
- /**
- * 將xml字串轉換為JSON對象
- * @param xmlFile xml字串
- * @return JSON對象
- */
- public JSON getJSONFromXml(String xmlString) {
- XMLSerializer xmlSerializer = new XMLSerializer();
- JSON json = xmlSerializer.read(xmlString);
- return json;
- }
Java代碼
- /**
- * 將xmlDocument轉換為JSON對象
- * @param xmlDocument XML Document
- * @return JSON對象
- */
- public JSON getJSONFromXml(Document xmlDocument) {
- String xmlString = xmlDocument.toString();
- return getJSONFromXml(xmlString);
- }
Java代碼
- /**
- * 將xml字串轉換為JSON字串
- * @param xmlString
- * @return JSON字串
- */
- public String getJSONStringFromXml(String xmlString ) {
- return getJSONFromXml(xmlString).toString();
- }
Java代碼
- /**
- * 將xmlDocument轉換為JSON字串
- * @param xmlDocument XML Document
- * @return JSON字串
- */
- public String getXMLtoJSONString(Document xmlDocument) {
- return getJSONStringFromXml(xmlDocument.toString());
- }
Java代碼
- /**
- * 讀取XML檔案准換為JSON字串
- * @param xmlFile XML檔案
- * @return JSON字串
- */
- public String getXMLFiletoJSONString(String xmlFile) {
- InputStream is = JsonUtil.class.getResourceAsStream(xmlFile);
- String xml;
- JSON json = null;
- try {
- xml = IOUtils.toString(is);
- XMLSerializer xmlSerializer = new XMLSerializer();
- json = xmlSerializer.read(xml);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return json.toString();
- }
Java代碼
- /**
- * 將Java對象轉換為JSON格式的字串
- *
- * @param javaObj
- * POJO,例如日誌的model
- * @return JSON格式的String字串
- */
- public static String getJsonStringFromJavaPOJO(Object javaObj) {
- return JSONObject.fromObject(javaObj).toString(1);
- }
Java代碼
- /**
- * 將Map准換為JSON字串
- * @param map
- * @return JSON字串
- */
- public static String getJsonStringFromMap(Map<?, ?> map) {
- JSONObject object = JSONObject.fromObject(map);
- return object.toString();
- }
xml轉json