Dependent Packages:
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
Input XML file, output JSON object
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 ();}}
/** * Convert XML string to JSON Object * @param xmlfile XML String * @return JSON Object */Public JSON Getjsonfromxml (string xmlstring) { XMLSerializer XMLSerializer = new XMLSerializer (); JSON json = Xmlserializer.read (xmlstring); return JSON;}
* Convert XmlDocument to JSON object * @param xmlDocument XML Document * @return JSON Object */Public JSON Getjsonfromxml (document xmlDocument) {String xmlstring = xmldocument.tostring (); return Getjsonfromxml (xmlstring);}
* Convert XML string to JSON string * @param xmlstring * @return JSON String */public string Getjsonstringfromxml (string xmlstring) {return Getjsonfromxml (xmlstring). toString ();}
/** * convert xmlDocument to JSON string * @param xmlDocument XML Document * @return JSON String */public string Getxmltojsonstri Ng (Document xmlDocument) {return getjsonstringfromxml (xmldocument.tostring ());}
* Read XML file for JSON string * @param xmlfile XML file * @return JSON String */public string getxmlfiletojsonstring (string Xmlfil E) {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 ();}
Converts a Java object to a JSON-formatted string * * @param javaobj * POJO, such as the model of the log * @return JSON-formatted string String */public static string Getjso Nstringfromjavapojo (Object javaobj) {return jsonobject.fromobject (javaobj). toString (1);}
change map to JSON string * @param map * @return JSON String */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)
The Java implementation of XML and JSON format conversion to each other