java使用SAX将XML转换为json类:
点击(此处)折叠或打开
- package com.mibridge.util;
- import net.sf.json.*;
- import org.apache.commons.lang.StringUtils;
- import org.xml.sax.*;
- import org.xml.sax.helpers.DefaultHandler;
- import java.util.ArrayList;
- import java.util.List;
- public class SAXJsonParser extends DefaultHandler {
- static final String TEXTKEY = "_text";
- JSONObject result;
- List stack;
- public SAXJsonParser() {
- }
- public JSONObject getJson() {
- return result;
- }
- public String attributeName(String name) {
- return "@" + name;
- }
- public void startDocument() throws SAXException {
- stack = new ArrayList();
- stack.add(0, new JSONObject());
- }
- public void endDocument() throws SAXException {
- result = stack.remove(0);
- }
- public void startElement(String uri, String localName, String qName,
- Attributes attributes) throws SAXException {
- JSONObject work = new JSONObject();
- for (int ix = 0; ix < attributes.getLength(); ix++)
- work.put(attributeName(attributes.getLocalName(ix)),
- attributes.getValue(ix));
- stack.add(0, work);
- }
- public void endElement(String uri, String localName, String qName)
- throws SAXException {
- JSONObject pop = stack.remove(0); // examine stack
- Object stashable = pop;
- if (pop.containsKey(TEXTKEY)) {
- String value = pop.getString(TEXTKEY).trim();
- if (pop.keySet().size() == 1)
- stashable = value; // single value
- else if (StringUtils.isBlank(value))
- pop.remove(TEXTKEY);
- }
- JSONObject parent = stack.get(0);
- if (!parent.containsKey(localName)) { // add new object
- parent.put(localName, stashable);
- } else { // aggregate into arrays
- Object work = parent.get(localName);
- if (work instanceof JSONArray) {
- ((JSONArray) work).add(stashable);
- } else {
- parent.put(localName, new JSONArray());
- parent.getJSONArray(localName).add(work);
- parent.getJSONArray(localName).add(stashable);
- }
- }
- }
- public void characters(char ch[], int start, int length)
- throws SAXException {
- JSONObject work = stack.get(0); // aggregate characters
- String value = (work.containsKey(TEXTKEY) ? work.getString(TEXTKEY)
- : "");
- work.put(TEXTKEY, value + new String(ch, start, length));
- }
- public void warning(SAXParseException e) throws SAXException {
- System.out.println("warning e=" + e.getMessage());
- }
- public void error(SAXParseException e) throws SAXException {
- System.err.println("error e=" + e.getMessage());
- }
- public void fatalError(SAXParseException e) throws SAXException {
- System.err.println("fatalError e=" + e.getMessage());
- throw e;
- }
- }
调用实例:
点击(此处)折叠或打开
- package com.mibridge.util;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.InputStream;
- import javax.xml.parsers.SAXParser;
- import javax.xml.parsers.SAXParserFactory;
- import net.sf.json.JSONObject;
- public class Xml2Json {
- /**
- * @param args
- */
- public static void main(String[] args) {
- try {
- InputStream stream = new FileInputStream("soap-origin.xml");
- JSONObject json = new JSONObject();
- json = xml2Json(stream);
- System.out.println(json.toString());
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static JSONObject xml2Json(InputStream stream) throws Exception {
- SAXParserFactory factory = SAXParserFactory.newInstance();
- factory.setNamespaceAware(true);
- SAXParser parser = factory.newSAXParser();
- SAXJsonParser handler = new SAXJsonParser();
- parser.parse(stream, handler);
- return handler.getJson();
- }
- }
执行上面的程序
xml文档:
点击(此处)折叠或打开
- <?xml version="1.0" encoding="utf-8"?>
- <soapenv:Envelope xmlns:soapenv="">
- <soapenv:Body>
- <ns:Response xmlns:ns="">
- <ns:return>
- <ns:person>
- <ns:personName></ns:personName>
- <ns:personAge></ns:personAge>
- <ns:personAddress>
- <ns:addressType>家庭住址</ns:addressType>
- <ns:addressLine1>中国深圳</ns:addressLine1>
- </ns:personAddress>
- <ns:personAddress>
- <ns:addressType>公司地址</ns:addressType>
- <ns:addressLine1>荔香公园</ns:addressLine1>
- </ns:personAddress>
- </ns:person>
- </ns:return>
- </ns:Response>
- </soapenv:Body>
- </soapenv:Envelope>
输出的json串:
- {"Envelope":{"Body":{"Response":{"return":{"person":{"personName":{},"personAge":{},"personAddress":[{"addressType":"家庭住址","addressLine1":"中国深圳"},{"addressType":"公司地址","addressLine1":"荔香公园"}]}}}}}}