本文整理汇总了Java中org.json.XML类的典型用法代码示例。如果您正苦于以下问题:Java XML类的具体用法?Java XML怎么用?Java XML使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
XML类属于org.json包,在下文中一共展示了XML类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: process
import org.json.XML; //导入依赖的package包/类
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);
}
}
示例2: convert
import org.json.XML; //导入依赖的package包/类
/**
* 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 "";
}
}
示例3: shouldHandleCommentsInXML
import org.json.XML; //导入依赖的package包/类
/**
* 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);
}
示例4: shouldHandleIllegalJSONNodeNames
import org.json.XML; //导入依赖的package包/类
/**
* Possible bug:
* Illegal node-names must be converted to legal XML-node-names.
* The given example shows 2 nodes which are valid for JSON, but not for XML.
* Therefore illegal arguments should be converted to e.g. an underscore (_).
*/
@Test
public void shouldHandleIllegalJSONNodeNames()
{
JSONObject inputJSON = new JSONObject();
inputJSON.append("123IllegalNode", "someValue1");
inputJSON.append("[email protected]", "someValue2");
String result = XML.toString(inputJSON);
/*
* This is invalid XML. Names should not begin with digits or contain
* certain values, including '@'. One possible solution is to replace
* illegal chars with '_', in which case the expected output would be:
* <___IllegalNode>someValue1</___IllegalNode><Illegal_node>someValue2</Illegal_node>
*/
String expected = "<123IllegalNode>someValue1</123IllegalNode><[email protected]>someValue2</[email protected]>";
assertEquals(expected, result);
}
示例5: jsonToXml
import org.json.XML; //导入依赖的package包/类
/**
* 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;
}
}
示例6: getAllZonesForDay
import org.json.XML; //导入依赖的package包/类
/**
* 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;
}
示例7: processXML2JSON
import org.json.XML; //导入依赖的package包/类
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;
}
示例8: fetch
import org.json.XML; //导入依赖的package包/类
@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);
}
}
示例9: xmlFromDOICrossRef
import org.json.XML; //导入依赖的package包/类
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();
}
示例10: resolve
import org.json.XML; //导入依赖的package包/类
/**
* 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);
}
}
示例11: resolve
import org.json.XML; //导入依赖的package包/类
/**
* 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);
}
}
示例12: convert
import org.json.XML; //导入依赖的package包/类
/**
* 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 "";
}
示例13: BlockDbH2Impl
import org.json.XML; //导入依赖的package包/类
/**
* 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");
}
示例14: XMLTextDecode
import org.json.XML; //导入依赖的package包/类
/**
* 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();
}
}
示例15: getResponse
import org.json.XML; //导入依赖的package包/类
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;
}