Converts XML to JSON (a SAX parsing instance) and jsonsax
The following is an example of converting XML into JSON,
Parse XML using SAX to generate the corresponding JSON string
Self-perception is still a common API, mainly including three classes
1,ToJsonSAXHandlerClass inherits the DefaultHandler class
The process of XML is responsible for processing the SAX event. The Code is as follows:
Java code
-
Package org. yjf. xmlToJson; import org. xml. sax. attributes; import org. xml. sax. SAXException; import org. xml. sax. helpers. defaultHandler; public class ToJsonSAXHandler extends DefaultHandler {// jsonStringBuilder saves the json string private StringBuilder jsonStringBuilder generated when parsing XML; /** isProcessing indicates whether an XML * startDocument event is being parsed. Set isProcessing = true * Set isProcessing = false */privat when the startDocument event occurs. E boolean isProcessing;/** justProcessStartElement indicates whether a startElement event has just been processed * introduces this tag to determine when a comma is output */private boolean justProcessStartElement; public ToJsonSAXHandler () {jsonStringBuilder = new StringBuilder () ;}@ Override public void startDocument () throws SAXException {/** set resolution statuses when parsing XML documents * Set isProcessing to true, indicates that XML is being parsed * setting justProcessStartElement to true, indicating that the startElement event has not been processed */I SProcessing = true; justProcessStartElement = true; // clear the character this in jsonStringBuilder. jsonStringBuilder. delete (0, this. jsonStringBuilder. length () ;}@ Override public void endDocument () throws SAXException {isProcessing = false ;}@ Override public void startElement (String uri, String localName, String qName, Attributes attrs) throws SAXException {/** indicates whether a startElement event has just been processed * If yes, this element is the first parent element. Element. * If not, it indicates that an endElement event has just been processed, that is, this element is not the first element of the parent element */if (! JustProcessStartElement) {jsonStringBuilder. append (','); justProcessStartElement = true;} jsonStringBuilder. append ("{"); jsonStringBuilder. append ("localName :"). append ('\"'). append (localName ). append ('\"'). append (','); jsonStringBuilder. append ("uri :"). append ('\"'). append (uri ). append ('\"'). append (','); jsonStringBuilder. append ("qName :"). append ('\"'). append (qName ). append ('\"'). append (','); // attributes of the parsed Elements Added to the JSON string jsonStringBuilder. append ("attrs: {"); if (attrs. getLength ()> 0) {jsonStringBuilder. append (attrs. getLocalName (0 )). append (":"). append (attrs. getValue (0); for (int I = 1; I <attrs. getLength (); I ++) {jsonStringBuilder. append (','). append (attrs. getLocalName (I )). append (":"). append (attrs. getValue (I) ;}} jsonStringBuilder. append ("},"); // Add the list of child elements of parsed elements to the JSON string jsonStringBuilder. append ("ChildElements :["). append ('\ n') ;}@ Override public void endElement (String uri, String localName, String qName) throws SAXException {justProcessStartElement = false; jsonStringBuilder. append ("]}"). append ('\ n') ;}@ Override public void characters (char [] ch, int begin, int length) throws SAXException {/** indicates whether a startElement event has just been processed * If yes, this element is the first element of the parent element. * If not, it indicates that an endElement event has just been processed, that is, this element is not the first element of the parent element */if (! JustProcessStartElement) {jsonStringBuilder. append (',');} else justProcessStartElement = false; jsonStringBuilder. append ('\ "'); for (int I = begin; I <begin + length; I ++) {switch (ch [I]) {case '\'': jsonStringBuilder. append ("\ '"); break; case' \ "': jsonStringBuilder. append ("\\\" "); break; case '\ N': jsonStringBuilder. append ("\ n"); break; case '\ t': jsonStringBuilder. append ("\ t"); break; case '\ R': jsonStringBuilder. append ("\ r"); break; default: jsonStringBuilder. append (ch [I]); break;} jsonStringBuilder. append ('\"'). append ('\ n');} public String getJsonString () throws XMLToJSONException {if (this. isProcessing) throw new XMLToJSONException ("getJsonString before resolution is finished"); else return jsonStringBuilder. toString ();}}
2. XMLToJSONException is an exception class (encapsulated exceptions that may occur during the conversion process). The Code is as follows:
Java code
package org.yjf.xmlToJson; public class XMLToJSONException extends Exception { private static final long serialVersionUID = 1L; public XMLToJSONException(){} public XMLToJSONException(String message){ super(message); } }
3,XMLToJSONClass is a tool class for converting XML into JSON strings
Java code
Package org. yjf. xmlToJson; import java. io. file; import java. io. fileInputStream; import java. io. IOException; import java. io. stringReader; import org. xml. sax. inputSource; import org. xml. sax. SAXException; import org. xml. sax. XMLReader; import org. xml. sax. helpers. XMLReaderFactory; public class XMLToJSON {public static String convert (String xmlStr) throws SAXException, IOException, XMLToJSONException {return convert (new InputSource (new StringReader (xmlStr )));} public static String convert (File file) throws SAXException, IOException, XMLToJSONException {return convert (new InputSource (new FileInputStream (file);} public static String convert (InputSource inputSource) throws SAXException, IOException, XMLToJSONException {ToJsonSAXHandler handler = new ToJsonSAXHandler (); // create a SAX Parser, set the content event processor and error event processor of this parser to handler XMLReader reader = XMLReaderFactory. createXMLReader (); reader. setContentHandler (handler); reader. setErrorHandler (handler); // parses the XML Input Source reader with the SAX Parser. parse (inputSource); // return the return handler, which is the json string saved in ToJsonSAXHandler. getJsonString ();}}
Test classTestAs shown below (because the generated JSON does not contain indentation, it may not seem intuitive, so I used the JSONObject class to print the JSON string with indentation, it also verifies that the converted JSON string is a valid JSON string ):
Java code
-
Package test; import java. io. file; import java. io. IOException; import org. json. JSONException; import org. json. JSONObject; import org. xml. sax. SAXException; import org. yjf. xmlToJson. XMLToJSON; import org. yjf. xmlToJson. XMLToJSONException; public class Test_1 {public static void main (String [] args) throws JSONException, SAXException, IOException, XMLToJSONException {String jsonStr = XMLToJSON. convert (new File ("books. xml ")); /** JSONObject is the java Implementation of a json object * you can use a valid JSON string to construct a JSON object * the following two lines of code construct a JSON string through the converted JSON string object, * The JSON object is printed with an indented string */JSONObject jsonObj = new JSONObject (jsonStr); System. out. println (jsonObj. toString (2 ));}}
Books. xmlThe content is as follows:
Xml Code
-
<?xml version="1.0" encoding="utf-8"?> <books count="2" xmlns="http://test.org/books"> <book id="1" page="1000"> <name>Thinking in JAVA</name> </book> <book id="2" page="800"> <name>Core JAVA2</name> </book> </books>
RunTestClass outputJSON stringAs follows:
{ "attrs": {"count": 2}, "childElements": [ "\n\t", { "attrs": { "id": 1, "page": 1000 }, "childElements": [ "\n\t\t", { "attrs": {}, "childElements": ["Thinking in JAVA"], "localName": "name", "qName": "name", "uri": "http://test.org/books" }, "\n\t" ], "localName": "book", "qName": "book", "uri": "http://test.org/books" }, "\n\t", { "attrs": { "id": 2, "page": 800 }, "childElements": [ "\n\t\t", { "attrs": {}, "childElements": ["Core JAVA2"], "localName": "name", "qName": "name", "uri": "http://test.org/books" }, "\n\t" ], "localName": "book", "qName": "book", "uri": "http://test.org/books" }, "\n" ], "localName": "books", "qName": "books", "uri": "http://test.org/books"}
Reference: http://www.iteye.com/topic/402083