Convert XML to JSON format

后端 未结 10 863
粉色の甜心
粉色の甜心 2020-12-13 07:43

I have to convert docx file format (which is in openXML format) into JSON format. I need some guidelines to do it. Thanks in advance.

相关标签:
10条回答
  • 2020-12-13 07:55

    Use

    xmlSerializer.setForceTopLevelObject(true)
    

    to include root element in resulting JSON.

    Your code would be like this

    String xml = "<hello><test>1.2</test><test2>123</test2></hello>";
    XMLSerializer xmlSerializer = new XMLSerializer();
    xmlSerializer.setForceTopLevelObject(true);
    JSON json = xmlSerializer.read(xml);
    
    0 讨论(0)
  • 2020-12-13 07:59

    Docx4j

    I've used docx4j before, and it's worth taking a look at.

    unXml

    You could also check out my open source unXml-library that is available on Maven Central.

    It is lightweight, and has a simple syntax to pick out XPaths from your xml, and get them returned as Json attributes in a Jackson ObjectNode.

    0 讨论(0)
  • 2020-12-13 08:05

    You may take a look at the Json-lib Java library, that provides XML-to-JSON conversion.

    String xml = "<hello><test>1.2</test><test2>123</test2></hello>";
    XMLSerializer xmlSerializer = new XMLSerializer();  
    JSON json = xmlSerializer.read( xml );  
    

    If you need the root tag too, simply add an outer dummy tag:

    String xml = "<hello><test>1.2</test><test2>123</test2></hello>";
    XMLSerializer xmlSerializer = new XMLSerializer();  
    JSON json = xmlSerializer.read("<x>" + xml + "</x>");  
    
    0 讨论(0)
  • 2020-12-13 08:07

    If you are dissatisfied with the various implementations, try rolling your own. Here is some code I wrote this afternoon to get you started. It works with net.sf.json and apache common-lang:

    static public JSONObject readToJSON(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();
    }
    

    And the SAXJsonParser implementation:

    package xml2json;
    
    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<JSONObject> stack;
    
        public SAXJsonParser(){}
        public JSONObject getJson(){return result;}
        public String attributeName(String name){return "@"+name;}
    
        public void startDocument () throws SAXException {
            stack = new ArrayList<JSONObject>();
            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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题