Java 类org.json.XML 实例源码

项目:yajwfs    文件:ShoutCastApi.java   
private void process(Response<String> response, ApiManagerInterface callback, Class clazz) {
    if (response.isSuccessful()) {
        String xml = response.body();
        try {
            JSONObject jsonObj;
            if (xml != null) {
                jsonObj = XML.toJSONObject(xml);
            } else {
                callback.onError(new IOException("response body is null"));
                return;
            }
            if (isVerboseLog) {
                System.out.println(jsonObj);
            }
            callback.onResult(new Gson().fromJson(jsonObj.toString(), clazz));
        } catch (JSONException e) {
            callback.onError(e);
            e.printStackTrace();
        }
    } else {
        handleUnsucceesfulResponse(response, callback);
    }
}
项目:xrd4j    文件:XMLToJSONConverter.java   
/**
 * Converts the given XML string to JSON string. class.
 *
 * @param data XML string
 * @return JSON string or an empty string if the conversion fails
 */
@Override
public String convert(String data) {
    LOGGER.debug("CONVERTING " + data);
    try {
        JSONObject asJson = XML.toJSONObject(data);
        if (asJson.has(ARRAY)) {
            // If the JSON object has an "array" key, it's an array
            JSONArray jsonArray = asJson.getJSONArray(ARRAY);
            LOGGER.debug("RETURN ARRAY " + jsonArray.toString());
            return jsonArray.toString();
        } else {
            // Did not have top-level array key.
            this.normalizeObject(asJson);
            String jsonStr = asJson.toString();
            // JSON-LD uses '@' characters in keys and they're not allowed
            // in XML element names. Replace '__at__' with '@' in keys.
            jsonStr = jsonStr.replaceAll("\"__at__(.+?\"\\s*:)", "\"@$1");
            LOGGER.debug("NORMALIZED TO " + jsonStr);
            return jsonStr;
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        LOGGER.warn("Converting XML to JSON failed! An empty String is returned.");
        return "";
    }
}
项目:usgin-geoportal    文件:XmlIoUtil.java   
/**
 * JSON To xml.
 * 
 * @param xmlString the xml string
 * @param rootElement the root element that the xml should have.  
 * By default = gptJsonXml
 * @return the xml. 
 * @throws Exception thrown if error while converting xmlString
 */
public static String jsonToXml(String xmlString, String rootElement) 
  throws Exception {
  try {
    JSONObject jso = new JSONObject(xmlString);
    rootElement = Val.chkStr(rootElement);
    if("".equals(rootElement)) {
      rootElement = "gptJsonXml";
    }
    String xml = XML.toString(jso, "gptJsonXml");
    StreamSource source = new StreamSource(new StringReader(xml));
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.transform(source, result);
    return Val.chkStr(writer.toString());
  } catch (Exception e) {
    throw e;
  }
}
项目:atl-pd-data    文件:Aggregation.java   
/**
 * Save incidents for a given day, returns if any data was added by this call.
 */
static final boolean getAllZonesForDay(final LocalDate localDate) throws Exception {
  JSONObject[] stats = new JSONObject[7];

  for (int zoneID = 1; zoneID <= 6; zoneID++) {
    stats[zoneID] = getStats(zoneID + "", localDate);
  }

  for (int zoneID = 1; zoneID <= 6; zoneID++) {
    JSONArray incidents = stats[zoneID].getJSONArray("incidents");
    if (incidents.length() == 0) {
      Utilities.println("halting getAllZonesForDay on " + localDate + " because zone " + zoneID + " is empty");
      return false;
    }
  }

  for (int zoneID = 1; zoneID <= 6; zoneID++) {
    String xmlString = "<stats>" + XML.toString(stats[zoneID]) + "</stats>";
    MongoData.addIncidentsToCollection(getIncidentsFromXMLString(xmlString));
  }

  return true;
}
项目:XML-JSON-MongoDB-Spring-Batch-Example    文件:JobConfiguration.java   
private String processXML2JSON(Path xmlDocPath) throws JSONException {


    String XML_STRING = null;
    try {
        XML_STRING = Files.lines(xmlDocPath).collect(Collectors.joining("\n"));
    } catch (IOException e) {
        e.printStackTrace();
    }

    JSONObject xmlJSONObj = XML.toJSONObject(XML_STRING);
    String jsonPrettyPrintString = xmlJSONObj.toString(PRETTY_PRINT_INDENT_FACTOR);
    System.out.println("PRINTING STRING :::::::::::::::::::::" + jsonPrettyPrintString);

    return jsonPrettyPrintString;
}
项目:GensokyoBot    文件:GensokyoInfoAgent.java   
@SuppressWarnings("UnusedReturnValue")
private static String fetch() {
    try {
        info = Unirest.get("https://gensokyoradio.net/xml").asString().getBody();

        JSONObject data = XML.toJSONObject(GensokyoInfoAgent.getInfo()).getJSONObject("GENSOKYORADIODATA");

        String newSong = data.getJSONObject("SONGINFO").getString("TITLE");

        if (!newSong.equals(lastSong)) {
            List<FredBoat> shards = FredBoat.getShards();
            for(FredBoat shard : shards) {
                shard.getJda().getPresence().setGame(Game.of(newSong));
            }

            log.info("Now playing " + newSong);
        }

        lastSong = data.getJSONObject("SONGINFO").getString("TITLE");

        return info;
    } catch (UnirestException e) {
        throw new RuntimeException(e);
    }
}
项目:bibliometrics    文件:AskAllServlet.java   
private Document xmlFromDOICrossRef(String doi) throws Exception {

        //send request to API
        MCRContent crossRefExport = crossRefConnection.getPublicationByDOI(doi);

        //transform JSON-response to XML
        MCRStringContent xml = new MCRStringContent(XML.toString(new JSONObject(crossRefExport.asString()), "content"));

        //transform xml to mods
        MCRXSL2XMLTransformer transformer = new MCRXSL2XMLTransformer("CrossRef2mods.xsl");
        MCRContent mods = transformer.transform(xml);

        return mods.asXML();
    }
项目:bibliometrics    文件:MCRIEEEResolver.java   
/**
 * Reads document description from the CrossRef API.
 *
 * 
 *   @author Eike Spielberg      
 *
 */

public Source resolve(String href, String base) throws TransformerException {
    String id = href.substring(href.indexOf(":") + 1);
    MCRContent content = null;
    IEEEConnector connection = new IEEEConnector();
    try {
        MCRContent ieeeExport = connection.getPublicationByAuthor(id);
        content = new MCRStringContent(XML.toString(new JSONObject(ieeeExport.asString()), "content"));
        LOGGER.debug("Reading MCRContent with DOI " + id);
        MCRXSL2XMLTransformer transformer = new MCRXSL2XMLTransformer("xsl/IEEE2mods.xsl");
        MCRContent mods = transformer.transform(content);
        connection.close();
        return mods.getSource();
    } catch (Exception e) {
        throw new TransformerException(e);
    }
}
项目:bibliometrics    文件:MCRCrossRefResolver.java   
/**
 * Reads document description from the CrossRef API.
 *
 * 
 *   @author Eike Spielberg      
 *
 */

public Source resolve(String href, String base) throws TransformerException {
    String id = href.substring(href.indexOf(":") + 1);
    MCRContent content = null;
    CrossRefConnector connection = new CrossRefConnector();
    try {
        MCRContent crossRefExport = connection.getPublicationByDOI(id);
        content = new MCRStringContent(XML.toString(new JSONObject(crossRefExport.asString()), "content"));
        LOGGER.debug("Reading MCRContent with DOI " + id);
        MCRXSL2XMLTransformer transformer = new MCRXSL2XMLTransformer("xsl/CrossRef2mods.xsl");
        MCRContent mods = transformer.transform(content);
        connection.close();
        return mods.getSource();
    } catch (Exception e) {
        throw new TransformerException(e);
    }
}
项目:xrd4j    文件:JSONToXMLConverter.java   
/**
 * Converts the given JSON string to XML string.
 * class.
 * @param data JSON string
 * @return XML string or an empty string if the conversion fails
 */
@Override
public String convert(String data) {
    String asXML;
    try {
        LOGGER.debug("CONVERTING " + data);
        if (data.startsWith("{")) {
            JSONObject asJson = new JSONObject(data);

            // "array" behaves in a special way, best to disallow it
            if (asJson.has("array")) {
                LOGGER.error("Data violation: Invalid key \"array\"");
                return "<error>Invalid key \"array\"</error>";
            }
            asXML = XML.toString(asJson);
        } else {
            asXML = XML.toString(new JSONArray(data));
        }
        // JSON-LD uses '@' characters in keys and they're not allowed
        // in XML element names. Replace '@' characters with '__at__' in
        // element names.
        asXML = asXML.replaceAll("<(/{0,1})@", "<$1__at__");
        LOGGER.debug("RETURN XML " + asXML);
        return asXML;
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    LOGGER.warn("Converting JSON to XML failed! An empty string is returned.");
    return "";
}
项目:neo-java    文件:BlockDbH2Impl.java   
/**
 * the constructor.
 *
 * @param config
 *            the configuration to use.
 */
public BlockDbH2Impl(final JSONObject config) {
    try (InputStream resourceAsStream = BlockDbH2Impl.class.getResourceAsStream(SQL_CACHE_XML);) {
        final String jsonStr = IOUtils.toString(resourceAsStream, "UTF-8");
        sqlCache = XML.toJSONObject(jsonStr, true).getJSONObject("BlockDbImpl");
    } catch (final IOException | NullPointerException e) {
        throw new RuntimeException("error reading resource\"" + SQL_CACHE_XML + "\" ", e);
    }

    fileSizeDir = new File(config.getString(ConfigurationUtil.FILE_SIZE_DIR));

    ds = new JdbcDataSource();
    ds.setUrl(config.getString(ConfigurationUtil.URL));

    final JdbcTemplate t = new JdbcTemplate(ds);

    executeSqlGroup(t, "create");
}
项目:appinventor-extensions    文件:Web.java   
/**
 * Decodes the given XML string to produce a list structure. <tag>string</tag> decodes to
 * a list that contains a pair of tag and string.  More generally, if obj1, obj2, ...
 * are tag-delimited XML strings, then <tag>obj1 obj2 ...</tag> decodes to a list
 * that contains a pair whose first element is tag and whose second element is the
 * list of the decoded obj's, ordered alphabetically by tags.  Examples:
 * <foo>123</foo> decodes to a one-item list containing the pair (foo, 123)
 * <foo>1 2 3</foo> decodes to a one-item list containing the pair (foo,"1 2 3")
 * <a><foo>1 2 3</foo><bar>456</bar></a> decodes to a list containing the pair
 * (a,X) where X is a 2-item list that contains the pair (bar,123) and the pair (foo,"1 2 3").
 * If the sequence of obj's mixes tag-delimited and non-tag-delimited
 * items, then the non-tag-delimited items are pulled out of the sequence and wrapped
 * with a "content" tag.  For example, decoding <a><bar>456</bar>many<foo>1 2 3</foo>apples</a>
 * is similar to above, except that the list X is a 3-item list that contains the additional pair
 * whose first item is the string "content", and whose second item is the list (many, apples).
 * This method signals an error and returns the empty list if the result is not well-formed XML.
 *
 * @param jsonText the JSON text to decode
 * @return the decoded text
 */
 // This method works by by first converting the XML to JSON and then decoding the JSON.
@SimpleFunction(description = "Decodes the given XML string to produce a list structure.  " +
    "See the App Inventor documentation on \"Other topics, notes, and details\" for information.")
// The above description string is punted because I can't figure out how to write the
// documentation string in a way that will look work both as a tooltip and in the autogenerated
// HTML for the component documentation on the Web.  It's too long for a tooltip, anyway.
public Object XMLTextDecode(String XmlText) {
  try {
    JSONObject json = XML.toJSONObject(XmlText);
    return JsonTextDecode(json.toString());
  } catch (JSONException e) {
    // We could be more precise and signal different errors for the conversion to JSON
    // versus the decoding of that JSON, but showing the actual error message should
    // be good enough.
    Log.e("Exception in XMLTextDecode", e.getMessage());
    form.dispatchErrorOccurredEvent(this, "XMLTextDecode",
        ErrorMessages.ERROR_WEB_JSON_TEXT_DECODE_FAILED, e.getMessage());
    // This XMLTextDecode should always return a list, even in the case of an error
    return YailList.makeEmptyList();
  }
}
项目:full-javaee-app    文件:CareerBuilder.java   
public static List<CareerBuilderJobSearchResult> getResponse (String candidateLocation, String jobQuery) {

    // Keywords matching CareerBuilder matched to Indeed : keywords = query, location = location, orderBy = sort, empType = jobType, pageNumber = start
    // perPage = limit, payLow = salary
    String keywords = "keywords=" + jobQuery, location = "location=" + candidateLocation, orderBy = "orderby=", empType = "emptype=", pageNumber = "pagenumber=",
            perPage = "perpage=" + preDefinedLimit, payLow = "paylow=", requestURL = "http://api.careerbuilder.com/v2/jobsearch?";

    // Master URL used to query CB database
    requestURL += developerKey + "&" + keywords + "&" + location + "&" + orderBy + "&" + empType + "&" + pageNumber + "&" + perPage + "&" + payLow;

       try {
           // Reading XML, converting to JSON
           String xml = CustomUtilities.RequestToString(requestURL);
           if (xml != null) {
               String json = XML.toJSONObject(xml).toString();
               Gson gson = new Gson();
               CareerBuilderMaster s = gson.fromJson(json, CareerBuilderMaster.class);
               return s.getResponse().getResult().getJobResults();
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
       return null;
}
项目:DeskChan    文件:CharacterPreset.java   
public void saveInFile(Path path) throws IOException {
    try {
        Document doc = DocumentBuilderFactory.newInstance()
                                             .newDocumentBuilder()
                                             .parse(new InputSource(new StringReader(XML.toString(toJSON()))));

        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        t.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
        OutputStreamWriter stream = new OutputStreamWriter(new FileOutputStream(path.resolve("saved.preset").toFile()), "UTF-8");
        t.transform(new DOMSource(doc), new StreamResult(stream));
    } catch(Exception ex){
        Main.log(ex);
        Main.log("Error while writing preset file");
    }
}
项目:DeskChan    文件:CharacterPreset.java   
public static CharacterPreset getFromFileUnsafe(Path path) {
    try {
        BufferedReader in = new BufferedReader(
                new InputStreamReader(new FileInputStream(path.toFile()), "UTF-8")
        );
        final StringBuilder str = new StringBuilder();
        String str2;
        while ((str2 = in.readLine()) != null) {
            str.append(str2);
            str.append("\n");
        }
        JSONObject obj = XML.toJSONObject(str.toString());
        return new CharacterPreset(obj.getJSONObject("preset"));
    } catch (Exception e) {
        Main.log(e);
        return new CharacterPreset();
    }
}
项目:beyondj    文件:MetricsVerticle.java   
protected org.json.JSONObject fetchDeploymentDescriptionsAsJSON() throws Exception {
    DeploymentDescriptions deploymentDescriptions = fetchDeploymentDescriptions();

    Iterator<DeploymentDescription> iterator = deploymentDescriptions.getDeploymentDescriptions().iterator();

    while (iterator.hasNext()) {
        DeploymentDescription deploymentDescription = iterator.next();
        if (!deploymentDescription.isEnableMetrics() ||
                deploymentDescription.isMetricsGateway() ||
                deploymentDescription.isSystemGateway()) {
            iterator.remove();
        }
    }

    Marshaller marshaller = descriptionJaxbContext.createMarshaller();
    StringWriter writer = new StringWriter();
    marshaller.marshal(deploymentDescriptions, writer);
    return XML.toJSONObject(writer.toString());
}
项目:beyondj    文件:MetricsVerticle.java   
protected org.json.JSONObject fetchMetricsAsJSON(MetricsRequest metricsRequest) throws Exception {
    MetricsResponse metricsResponse = ServiceDownloadUtil.downloadMetrics(config, metricsRequest);

    String payloadStr = metricsResponse.getPayload();

    String payload = StringEscapeUtils.unescapeXml(payloadStr);

    payload = payload.replaceAll("[()]", "");

    payload = payload.replace("metrics_content", "");

    org.json.JSONObject jsonObject = new org.json.JSONObject();
    Marshaller marshaller = metricsRequestJaxbContext.createMarshaller();
    StringWriter writer = new StringWriter();
    marshaller.marshal(metricsRequest, writer);
    jsonObject.put(METRICS_REQUEST, XML.toJSONObject(writer.toString()));
    jsonObject.put(PAYLOAD, payload);
    return jsonObject;
}
项目:LAS    文件:ConfigService.java   
public static void sendError(HttpServletResponse response, String container, String format, String message) {
    PrintWriter respout;
    String xml = "<"+container+"><status>error</status><error>"+message+"</error></"+container+">";
    try {
        if ( format.equals("xml") ) {
            respout = response.getWriter();
        } else {
            respout = response.getWriter();
            JSONObject json_response = XML.toJSONObject(xml);
            json_response.write(respout);
        }
    } catch (Exception e) {
        // At this point we're toast and no error message will be generated.
        log.error("Error in JSON response: "+e.getMessage());
    } 
}
项目:momo-discord-old    文件:AnimeSearch.java   
private JsonValue getMalJson(String search) throws NoAPIKeyException, IOException {
    try {
        String query = baseMalUrl + "anime/search.xml?q=" + URLEncoder.encode(search, "UTF-8");
        HttpsURLConnection conn = (HttpsURLConnection) new URL(query).openConnection();
        String userpass;

        userpass = Bot.getInstance().getApiKeys().get("maluser") + ":" 
                + Bot.getInstance().getApiKeys().get("malpass");

        String basicAuth = "Basic " + new String(Base64.encodeBase64String(userpass.getBytes()));
        conn.setRequestProperty("Authorization", basicAuth);
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36");
        conn.connect();
        StringBuilder stb = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = rd.readLine()) != null) {
            stb.append(line);
        }
        return Json.parse(XML.toJSONObject(stb.toString()).toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
项目:full-javaee-app    文件:CustomUtilities.java   
public static JSONObject XMLToJSONObject(String xml) {
    if (xml != null && !xml.isEmpty()) {
        try {
            return XML.toJSONObject(xml);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}
项目:full-javaee-app    文件:CareerBuilder.java   
public static List<CareerBuilderJobSearchResult> getResponse (String candidateLocation, String jobQuery) {

    // Keywords matching CareerBuilder matched to Indeed : keywords = query, location = location, orderBy = sort, empType = jobType, pageNumber = start
    // perPage = limit, payLow = salary
    String keywords = "keywords=" + jobQuery, location = "location=" + candidateLocation, orderBy = "orderby=", empType = "emptype=", pageNumber = "pagenumber=",
            perPage = "perpage=" + preDefinedLimit, payLow = "paylow=", requestURL = "http://api.careerbuilder.com/v2/jobsearch?";

    // Master URL used to query CB database
    requestURL += developerKey + "&" + keywords + "&" + location + "&" + orderBy + "&" + empType + "&" + pageNumber + "&" + perPage + "&" + payLow;

       try {
           // Reading XML, converting to JSON
           String xml = CustomUtilities.RequestToString(requestURL);
           if (xml != null) {
               String json = XML.toJSONObject(xml).toString();
               Gson gson = new Gson();
               CareerBuilderMaster s = gson.fromJson(json, CareerBuilderMaster.class);
               return s.getResponse().getResult().getJobResults();
           }
       } catch (Exception e) {
           e.printStackTrace();
       }
       return null;
}
项目:cloud-concur-expenses-ext    文件:ExpensesServlet.java   
/**
 * Extracts the contents of a HttpURLConnection's InputStream and converts it to a Json-formatted string
 */
private String getJsonResult(HttpURLConnection urlConnection) throws IOException {
    InputStream apiInStream = urlConnection.getInputStream();
    String xmlContentFromStream = getStringFromStream(apiInStream);
    JSONObject jsonObject = XML.toJSONObject(xmlContentFromStream);
    return jsonObject.toString(INDENT_FACTOR);
}
项目:CDMTableBrowser    文件:PredictionsServlet.java   
private void sendResponse(HttpServletResponse response, String payload, boolean json) {
try {
    // Convert to JSON?
    if (json) {
    JSONObject jobt = XML.toJSONObject(payload);
    payload = jobt.toString(3); // 3 is indentation level for nice look
    }

    OutputStream out = response.getOutputStream();
    out.write(payload.getBytes());
    out.flush();
}
catch(Exception e) {
    throw new HTTPException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
   }
项目:CDMTableBrowser    文件:PredictionsServlet.java   
private void sendResponse(HttpServletResponse response, String payload, boolean json) {
try {
    // Convert to JSON?
    if (json) {
    JSONObject jobt = XML.toJSONObject(payload);
    payload = jobt.toString(3); // 3 is indentation level for nice look
    }

    OutputStream out = response.getOutputStream();
    out.write(payload.getBytes());
    out.flush();
}
catch(Exception e) {
    throw new HTTPException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
   }
项目:CrawlerPack    文件:CrawlerPack.java   
/**
 * 將 json 轉為 XML
 *
 * @param json a json format string.
 * @return XML format string
 */
public String jsonToXml(String json){
    String xml = "";
    // 處理直接以陣列開頭的JSON,並指定給予 row 的 tag
    if ( "[".equals( json.substring(0,1) ) ){
        xml = XML.toString(new JSONArray(json), "row");
    }else{
        xml = XML.toString(new JSONObject(json));
    }

    return xml;
}
项目:apiman-plugins    文件:JsonToXmlTransformer.java   
@Override
   public String transform(String json) {
String ROOT = null;
       JSONObject jsonObject = null;
    if (json.trim().startsWith("{")) { //$NON-NLS-1$
        jsonObject = new JSONObject(json);
        if (jsonObject.length() > 1) {
            ROOT = "root"; //$NON-NLS-1$
        }
    } else {
        JSONArray jsonArray = new JSONArray(json);
        jsonObject = new JSONObject().put(ELEMENT, jsonArray);
        ROOT = "root";  //$NON-NLS-1$
    }
       return XML.toString(jsonObject, ROOT);
}
项目:relax-dms    文件:DocumentServiceImpl.java   
@Override
public String jsonToXml(JsonNode json) {
    // remove attachments
    ((ObjectNode) json).remove("_attachments");

    // convert to JSONObject and add root element
    JSONObject jsonObject = new JSONObject(json.toString());
    JSONObject rootObject= new JSONObject();
    rootObject.put("document", jsonObject);

    String xml = XML.toString(rootObject);
    return xml;
}
项目:JSON-Java-unit-test    文件:XMLTest.java   
/**
 * JSONObject from a null XML string.
 * Expects a NullPointerException
 */
@Test(expected=NullPointerException.class)
public void shouldHandleNullXML() {
    String xmlStr = null;
    JSONObject jsonObject = XML.toJSONObject(xmlStr);
    assertTrue("jsonObject should be empty", jsonObject.length() == 0);
}
项目:JSON-Java-unit-test    文件:XMLTest.java   
/**
 * Empty JSONObject from an empty XML string.
 */
@Test
public void shouldHandleEmptyXML() {

    String xmlStr = "";
    JSONObject jsonObject = XML.toJSONObject(xmlStr);
    assertTrue("jsonObject should be empty", jsonObject.length() == 0);
}
项目:JSON-Java-unit-test    文件:XMLTest.java   
/**
 * Empty JSONObject from a non-XML string.
 */
@Test
public void shouldHandleNonXML() {
    String xmlStr = "{ \"this is\": \"not xml\"}";
    JSONObject jsonObject = XML.toJSONObject(xmlStr);
    assertTrue("xml string should be empty", jsonObject.length() == 0);
}
项目:JSON-Java-unit-test    文件:XMLTest.java   
/**
 * Invalid XML string (tag contains a frontslash).
 * Expects a JSONException
 */
@Test
public void shouldHandleInvalidSlashInTag() {
    String xmlStr = 
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
        "<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
        "   xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
        "    <address>\n"+
        "       <name/x>\n"+
        "       <street>abc street</street>\n"+
        "   </address>\n"+
        "</addresses>";
    try {
        XML.toJSONObject(xmlStr);
        fail("Expecting a JSONException");
    } catch (JSONException e) {
        assertEquals("Expecting an exception message",
                "Misshaped tag at 176 [character 14 line 4]",
                e.getMessage());
    }
}
项目:JSON-Java-unit-test    文件:XMLTest.java   
/**
 * Invalid XML string ('!' char in tag)
 * Expects a JSONException
 */
@Test
public void shouldHandleInvalidBangInTag() {
    String xmlStr = 
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
        "<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
        "   xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
        "    <address>\n"+
        "       <name/>\n"+
        "       <!>\n"+
        "   </address>\n"+
        "</addresses>";
    try {
        XML.toJSONObject(xmlStr);
        fail("Expecting a JSONException");
    } catch (JSONException e) {
        assertEquals("Expecting an exception message",
                "Misshaped meta tag at 214 [character 12 line 7]",
                e.getMessage());
    }
}
项目:JSON-Java-unit-test    文件:XMLTest.java   
/**
 * Invalid XML string ('!' char and no closing tag brace)
 * Expects a JSONException
 */
@Test
public void shouldHandleInvalidBangNoCloseInTag() {
    String xmlStr = 
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
        "<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
        "   xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
        "    <address>\n"+
        "       <name/>\n"+
        "       <!\n"+
        "   </address>\n"+
        "</addresses>";
    try {
        XML.toJSONObject(xmlStr);
        fail("Expecting a JSONException");
    } catch (JSONException e) {
        assertEquals("Expecting an exception message",
                "Misshaped meta tag at 213 [character 12 line 7]",
                e.getMessage());
    }
}
项目:JSON-Java-unit-test    文件:XMLTest.java   
/**
 * Invalid XML string (no end brace for tag)
 * Expects JSONException
 */
@Test
public void shouldHandleNoCloseStartTag() {
    String xmlStr = 
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
        "<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
        "   xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
        "    <address>\n"+
        "       <name/>\n"+
        "       <abc\n"+
        "   </address>\n"+
        "</addresses>";
    try {
        XML.toJSONObject(xmlStr);
        fail("Expecting a JSONException");
    } catch (JSONException e) {
        assertEquals("Expecting an exception message",
                "Misplaced '<' at 193 [character 4 line 6]",
                e.getMessage());
    }
}
项目:JSON-Java-unit-test    文件:XMLTest.java   
/**
 * Invalid XML string (partial CDATA chars in tag name)
 * Expects JSONException
 */
@Test
public void shouldHandleInvalidCDATABangInTag() {
    String xmlStr = 
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
        "<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
        "   xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
        "    <address>\n"+
        "       <name>Joe Tester</name>\n"+
        "       <![[]>\n"+
        "   </address>\n"+
        "</addresses>";
    try {
        XML.toJSONObject(xmlStr);
        fail("Expecting a JSONException");
    } catch (JSONException e) {
        assertEquals("Expecting an exception message",
                "Expected 'CDATA[' at 204 [character 11 line 5]",
                e.getMessage());
    }
}
项目:JSON-Java-unit-test    文件:XMLTest.java   
/**
 * No SML start tag. The ending tag ends up being treated as content.
 */
@Test
public void shouldHandleNoStartTag() {
    String xmlStr = 
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
        "<addresses xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""+
        "   xsi:noNamespaceSchemaLocation='test.xsd'>\n"+
        "    <address>\n"+
        "       <name/>\n"+
        "       <nocontent/>>\n"+
        "   </address>\n"+
        "</addresses>";
    String expectedStr = 
        "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+
        "content\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+
        "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}";
    JSONObject jsonObject = XML.toJSONObject(xmlStr);
    JSONObject expectedJsonObject = new JSONObject(expectedStr);
    Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
项目:JSON-Java-unit-test    文件:XMLTest.java   
/**
 * Valid XML with comments to JSONObject
 */
@Test
public void shouldHandleCommentsInXML() {

    String xmlStr = 
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"+
            "<!-- this is a comment -->\n"+
            "<addresses>\n"+
            "   <address>\n"+
            "       <![CDATA[ this is -- <another> comment ]]>\n"+
            "       <name>Joe Tester</name>\n"+
            "       <!-- this is a - multi line \n"+
            "            comment -->\n"+
            "       <street>Baker street 5</street>\n"+
            "   </address>\n"+
            "</addresses>";
    JSONObject jsonObject = XML.toJSONObject(xmlStr);
    String expectedStr = "{\"addresses\":{\"address\":{\"street\":\"Baker "+
            "street 5\",\"name\":\"Joe Tester\",\"content\":\" this is -- "+
            "<another> comment \"}}}";
    JSONObject expectedJsonObject = new JSONObject(expectedStr);
    Util.compareActualVsExpectedJsonObjects(jsonObject,expectedJsonObject);
}
项目:JSON-Java-unit-test    文件:XMLTest.java   
/**
 * Converting a JSON doc containing '>' content to JSONObject, then
 * XML.toString() should result in valid XML.
 */
@Test
public void shouldHandleContentNoArraytoString() {
    String expectedStr = 
        "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+
        "content\":\">\"},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+
        "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}";
    JSONObject expectedJsonObject = new JSONObject(expectedStr);
    String finalStr = XML.toString(expectedJsonObject);
    String expectedFinalStr = "<addresses><address><name/><nocontent/>&gt;"+
            "</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+
            "spaceSchemaLocation><xmlns:xsi>http://www.w3.org/2001/XMLSche"+
            "ma-instance</xmlns:xsi></addresses>";
    assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+
            finalStr+"]", expectedFinalStr.equals(finalStr));
}
项目:JSON-Java-unit-test    文件:XMLTest.java   
/**
 * Converting a JSON doc containing a 'content' array to JSONObject, then
 * XML.toString() should result in valid XML.
 * TODO: This is probably an error in how the 'content' keyword is used.
 */
@Test
public void shouldHandleContentArraytoString() {
    String expectedStr = 
        "{\"addresses\":{\"address\":{\"name\":\"\",\"nocontent\":\"\",\""+
        "content\":[1, 2, 3]},\"xsi:noNamespaceSchemaLocation\":\"test.xsd\",\""+
        "xmlns:xsi\":\"http://www.w3.org/2001/XMLSchema-instance\"}}";
    JSONObject expectedJsonObject = new JSONObject(expectedStr);
    String finalStr = XML.toString(expectedJsonObject);
    String expectedFinalStr = "<addresses><address><name/><nocontent/>"+
            "1\n2\n3"+
            "</address><xsi:noNamespaceSchemaLocation>test.xsd</xsi:noName"+
            "spaceSchemaLocation><xmlns:xsi>http://www.w3.org/2001/XMLSche"+
            "ma-instance</xmlns:xsi></addresses>";
    assertTrue("Should handle expectedFinal: ["+expectedStr+"] final: ["+
            finalStr+"]", expectedFinalStr.equals(finalStr));
}