標籤:main exce span null json對象 utils convert exception div
依賴的包:
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對象
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();}}
/** * 將xml字串轉換為JSON對象 * @param xmlFile xml字串 * @return JSON對象*/ public JSON getJSONFromXml(String xmlString) { XMLSerializer xmlSerializer = new XMLSerializer(); JSON json = xmlSerializer.read(xmlString); return json;}
/** * 將xmlDocument轉換為JSON對象 * @param xmlDocument XML Document * @return JSON對象*/ public JSON getJSONFromXml(Document xmlDocument) { String xmlString = xmlDocument.toString(); return getJSONFromXml(xmlString);}
/** * 將xml字串轉換為JSON字串 * @param xmlString * @return JSON字串*/ public String getJSONStringFromXml(String xmlString ) { return getJSONFromXml(xmlString).toString();}
/** * 將xmlDocument轉換為JSON字串 * @param xmlDocument XML Document * @return JSON字串*/ public String getXMLtoJSONString(Document xmlDocument) { return getJSONStringFromXml(xmlDocument.toString());}
/** * 讀取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對象轉換為JSON格式的字串* * @param javaObj * POJO,例如日誌的model * @return JSON格式的String字串*/ public static String getJsonStringFromJavaPOJO(Object javaObj) { return JSONObject.fromObject(javaObj).toString(1);}
/** * 將Map准換為JSON字串 * @param map * @return JSON字串*/ public static String getJsonStringFromMap(Map<?, ?> map) { JSONObject object = JSONObject.fromObject(map); return object.toString();}
- ezmorph-1.0.6.jar (84.5 KB)
- commons-io-1.3.2.jar (85.7 KB)
- commons-lang-2.1.jar (202.9 KB)
- json-lib-2.4-jdk15.jar (155.4 KB)
xml和JSON格式相互轉換的Java實現