本文整理汇总了Java中org.json.XML.toJSONObject方法的典型用法代码示例。如果您正苦于以下问题:Java XML.toJSONObject方法的具体用法?Java XML.toJSONObject怎么用?Java XML.toJSONObject使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.json.XML
的用法示例。
在下文中一共展示了XML.toJSONObject方法的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: 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;
}
示例5: 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();
}
}
示例6: getFromFileUnsafe
import org.json.XML; //导入方法依赖的package包/类
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();
}
}
示例7: fetchDeploymentDescriptionsAsJSON
import org.json.XML; //导入方法依赖的package包/类
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());
}
示例8: sendError
import org.json.XML; //导入方法依赖的package包/类
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());
}
}
示例9: XMLToJSONObject
import org.json.XML; //导入方法依赖的package包/类
public static JSONObject XMLToJSONObject(String xml) {
if (xml != null && !xml.isEmpty()) {
try {
return XML.toJSONObject(xml);
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
示例10: getJsonResult
import org.json.XML; //导入方法依赖的package包/类
/**
* 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);
}
示例11: sendResponse
import org.json.XML; //导入方法依赖的package包/类
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);
}
}
示例12: shouldHandleNullXML
import org.json.XML; //导入方法依赖的package包/类
/**
* 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);
}
示例13: shouldHandleEmptyXML
import org.json.XML; //导入方法依赖的package包/类
/**
* 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);
}
示例14: shouldHandleNonXML
import org.json.XML; //导入方法依赖的package包/类
/**
* 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);
}
示例15: shouldHandleInvalidSlashInTag
import org.json.XML; //导入方法依赖的package包/类
/**
* 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());
}
}