Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2566408
  • 博文数量: 245
  • 博客积分: 4125
  • 博客等级: 上校
  • 技术积分: 3113
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-25 23:56
文章分类

全部博文(245)

文章存档

2015年(2)

2014年(26)

2013年(41)

2012年(40)

2011年(134)

2010年(2)

分类: Java

2012-10-29 22:48:40

java使用SAX将XML转换为json类:

点击(此处)折叠或打开

  1. package com.mibridge.util;

  2. import net.sf.json.*;
  3. import org.apache.commons.lang.StringUtils;
  4. import org.xml.sax.*;
  5. import org.xml.sax.helpers.DefaultHandler;
  6. import java.util.ArrayList;
  7. import java.util.List;

  8. public class SAXJsonParser extends DefaultHandler {

  9.     static final String TEXTKEY = "_text";

  10.     JSONObject result;
  11.     List stack;

  12.     public SAXJsonParser() {
  13.     }

  14.     public JSONObject getJson() {
  15.         return result;
  16.     }

  17.     public String attributeName(String name) {
  18.         return "@" + name;
  19.     }

  20.     public void startDocument() throws SAXException {
  21.         stack = new ArrayList();
  22.         stack.add(0, new JSONObject());
  23.     }

  24.     public void endDocument() throws SAXException {
  25.         result = stack.remove(0);
  26.     }

  27.     public void startElement(String uri, String localName, String qName,
  28.             Attributes attributes) throws SAXException {
  29.         JSONObject work = new JSONObject();
  30.         for (int ix = 0; ix < attributes.getLength(); ix++)
  31.             work.put(attributeName(attributes.getLocalName(ix)),
  32.                     attributes.getValue(ix));
  33.         stack.add(0, work);
  34.     }

  35.     public void endElement(String uri, String localName, String qName)
  36.             throws SAXException {
  37.         JSONObject pop = stack.remove(0); // examine stack
  38.         Object stashable = pop;
  39.         if (pop.containsKey(TEXTKEY)) {
  40.             String value = pop.getString(TEXTKEY).trim();
  41.             if (pop.keySet().size() == 1)
  42.                 stashable = value; // single value
  43.             else if (StringUtils.isBlank(value))
  44.                 pop.remove(TEXTKEY);
  45.         }
  46.         JSONObject parent = stack.get(0);
  47.         if (!parent.containsKey(localName)) { // add new object
  48.             parent.put(localName, stashable);
  49.         } else { // aggregate into arrays
  50.             Object work = parent.get(localName);
  51.             if (work instanceof JSONArray) {
  52.                 ((JSONArray) work).add(stashable);
  53.             } else {
  54.                 parent.put(localName, new JSONArray());
  55.                 parent.getJSONArray(localName).add(work);
  56.                 parent.getJSONArray(localName).add(stashable);
  57.             }
  58.         }
  59.     }

  60.     public void characters(char ch[], int start, int length)
  61.             throws SAXException {
  62.         JSONObject work = stack.get(0); // aggregate characters
  63.         String value = (work.containsKey(TEXTKEY) ? work.getString(TEXTKEY)
  64.                 : "");
  65.         work.put(TEXTKEY, value + new String(ch, start, length));
  66.     }

  67.     public void warning(SAXParseException e) throws SAXException {
  68.         System.out.println("warning e=" + e.getMessage());
  69.     }

  70.     public void error(SAXParseException e) throws SAXException {
  71.         System.err.println("error e=" + e.getMessage());
  72.     }

  73.     public void fatalError(SAXParseException e) throws SAXException {
  74.         System.err.println("fatalError e=" + e.getMessage());
  75.         throw e;
  76.     }
  77. }

调用实例:


点击(此处)折叠或打开

  1. package com.mibridge.util;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.InputStream;
  5. import javax.xml.parsers.SAXParser;
  6. import javax.xml.parsers.SAXParserFactory;
  7. import net.sf.json.JSONObject;
  8. public class Xml2Json {
  9. /**
  10. * @param args
  11. */
  12. public static void main(String[] args) {
  13. try {
  14. InputStream stream = new FileInputStream("soap-origin.xml");
  15. JSONObject json = new JSONObject();
  16. json = xml2Json(stream);
  17. System.out.println(json.toString());
  18. } catch (FileNotFoundException e) {
  19. e.printStackTrace();
  20. } catch (Exception e) {
  21. e.printStackTrace();
  22. }
  23. }
  24. public static JSONObject xml2Json(InputStream stream) throws Exception {
  25. SAXParserFactory factory = SAXParserFactory.newInstance();
  26. factory.setNamespaceAware(true);
  27. SAXParser parser = factory.newSAXParser();
  28. SAXJsonParser handler = new SAXJsonParser();
  29. parser.parse(stream, handler);
  30. return handler.getJson();
  31. }
  32. }

执行上面的程序

xml文档:


点击(此处)折叠或打开

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <soapenv:Envelope xmlns:soapenv="">
  3. <soapenv:Body>
  4. <ns:Response xmlns:ns="">
  5.    <ns:return>
  6.       <ns:person>
  7.          <ns:personName></ns:personName>
  8.          <ns:personAge></ns:personAge>
  9.          <ns:personAddress>
  10.             <ns:addressType>家庭住址</ns:addressType>
  11.             <ns:addressLine1>中国深圳</ns:addressLine1>
  12.          </ns:personAddress>
  13.          <ns:personAddress>
  14.             <ns:addressType>公司地址</ns:addressType>
  15.             <ns:addressLine1>荔香公园</ns:addressLine1>
  16.          </ns:personAddress>
  17.       </ns:person>
  18.    </ns:return>
  19. </ns:Response>
  20. </soapenv:Body>
  21. </soapenv:Envelope>

输出的json串:


  1. {"Envelope":{"Body":{"Response":{"return":{"person":{"personName":{},"personAge":{},"personAddress":[{"addressType":"家庭住址","addressLine1":"中国深圳"},{"addressType":"公司地址","addressLine1":"荔香公园"}]}}}}}}

阅读(2687) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~