Example usage for org.json XML toString

List of usage examples for org.json XML toString

Introduction

In this page you can find the example usage for org.json XML toString.

Prototype

public static String toString(Object object) throws JSONException 

Source Link

Document

Convert a JSONObject into a well-formed, element-normal XML string.

Usage

From source file:es.upm.dit.xsdinferencer.extraction.extractorImpl.JSONTypesExtractorImpl.java

/**
 * Method that performs the conversion between JSON and XML
 * @param jsonRoot the root of the JSON document. It must be either a {@link JSONObject} or a {@link JSONArray}
 * @param namespaceRoot the namespace of the resulting root element
 * @return a JDOM2 {@link Document} representing the obtained XML.
 * @throws JDOMException/*from w w w. j  av  a2  s  .  c o  m*/
 * @throws IOException
 */
protected Document convertJSONToXML(Object jsonRoot, Namespace namespaceRoot)
        throws JDOMException, IOException {
    if (!(jsonRoot instanceof JSONArray || jsonRoot instanceof JSONObject)) {
        throw new IllegalArgumentException("'jsonRoot' must be either a JSONObject or a JSONArray");
    }
    quoteStringsAtJSON(jsonRoot);
    addPrefixToJSONKeysEndingsRecursive(jsonRoot, XSDInferenceConfiguration.ARRAY_ELEMENT_NAME,
            XSDInferenceConfiguration.ARRAY_ELEMENT_ESCAPING_PREFIX);
    encapsulateArraysAtJSONRecursive(jsonRoot);
    String xmlString = "<" + XSDInferenceConfiguration.XML_ROOT_NAME + ">" + XML.toString(jsonRoot) + "</"
            + XSDInferenceConfiguration.XML_ROOT_NAME + ">";
    SAXBuilder saxBuilder = new SAXBuilder();
    Document xmlDocument = saxBuilder.build(new StringReader(xmlString));
    setNamespaceToElementsByName(XSDInferenceConfiguration.ARRAY_ELEMENT_NAME, xmlDocument.getRootElement(),
            XSDInferenceConfiguration.NAMESPACE_ARRAY_ELEMENT);
    removePrefixToElementNameEndings(xmlDocument.getRootElement(), XSDInferenceConfiguration.ARRAY_ELEMENT_NAME,
            XSDInferenceConfiguration.ARRAY_ELEMENT_ESCAPING_PREFIX);
    xmlDocument.getRootElement().setNamespace(namespaceRoot);
    sortElementsRecursive(xmlDocument.getRootElement());
    return xmlDocument;
}