1. The first method uses JSON-java provides a method that has been used before json-Lib provides a way to JSON, later discovered this open source project, found that it is very good to use, and can modify the parse method in the Xml.java to meet their own conversion needs. (1first go to git to download the required Java files and import the project Git:https://Github.com/stleary/json-java(2The XML-to-JSON conversion is done using the Xml.tojsonobject (XML) method provided in Xml.java, and JSON can also be formatted [Java] View plain copy/*the first method, using the method provided by Json-java*/ //Convert XML to JSONJsonobject xmljsonobj =Xml.tojsonobject (XML); //Set IndentString jsonprettyprintstring = xmljsonobj.tostring (4); //Output formatted JSONSystem. out. println (jsonprettyprintstring); 2. The second method uses JSON-Lib's XmlSerializer object (1) to create a XmlSerializer object (2use XmlSerializer's Read (XML) method to [Java] View plain copy/*the second method, using the method provided by Json-lib*/ //Create a XmlSerializer objectXMLSerializer XMLSerializer =NewXMLSerializer (); //Convert XML to JSON (note: If it is an attribute of an element, it will have an @ identifier in front of the key in the JSON)String result =xmlserializer.read (XML). toString (); //Output JSON contentSystem. out. println (Result); 3. Test [Java] View plain copy Public classTest { Public Static voidMain (string[] args) {String XML="<class id="+"' 1 '"+"><student><name>aaaaaa</name><age>21</age></student><student> <name>bbbbbb</name><age>22</age></student></class>"; /*the first method, using the method provided by Json-java*/ //Convert XML to JSONJsonobject xmljsonobj =Xml.tojsonobject (XML); //Set IndentString jsonprettyprintstring = xmljsonobj.tostring (4); //Output formatted JSONSystem. out. println (jsonprettyprintstring); /*the second method, using the method provided by Json-lib*/ //Create a XmlSerializer objectXMLSerializer XMLSerializer =NewXMLSerializer (); //Convert XML to JSON (note: If it is an attribute of an element, it will have an @ identifier in front of the key in the JSON)String result =xmlserializer.read (XML). toString (); //Output JSON contentSystem. out. println (Result); The first method output: [Java] View plain copy {"class": { "ID":1, "Student": [ { " Age": +, "name":"aaaaaa" }, { " Age": A, "name":"bbbbbb"}]}} The second method output: [Java] View plain copy {"@id":"1","Student":[{"name":"aaaaaa"," Age":" +"},{"name":"bbbbbb"," Age":" A"}]} source code download: http://download.csdn.net/detail/lom9357bye/9690304Reference: http://hw1287789687.iteye.com/blog/2229267http://heshans.blogspot.com/2014/01/java-library-to-convert-xml-to-json.html
Methods of XML to JSON