本文整理匯總了Java中net.sf.json.JSON類的典型用法代碼示例。如果您正苦於以下問題:Java JSON類的具體用法?Java JSON怎麽用?Java JSON使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
JSON類屬於net.sf.json包,在下文中一共展示了JSON類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。
示例1: extractErrorMessage
import net.sf.json.JSON; //導入依賴的package包/類
@Override
protected String extractErrorMessage(String response) {
if (response != null && !response.isEmpty()) {
try {
JSON jsonResponse = JSONSerializer.toJSON(response, new JsonConfig());
if (jsonResponse instanceof JSONObject) {
JSONObject object = (JSONObject) jsonResponse;
JSONObject errorObj = object.getJSONObject("error");
if (errorObj.containsKey("message")) {
return errorObj.getString("message");
}
}
} catch (JSONException ex) {
log.debug("Cannot parse JSON error response: " + response);
}
}
return response;
}
示例2: testInstantiateGlobalConfigData
import net.sf.json.JSON; //導入依賴的package包/類
@Test
public void testInstantiateGlobalConfigData() {
JSONObject json = new JSONObject();
json.put("listOfGlobalConfigData", JSONArray.fromObject("[{\"name\":\"Sonar\",\"url\":\"http://localhost:9000\",\"account\":\"admin\",\"password\":\"admin\"}]"));
JSON globalDataConfig = (JSON) json.opt("listOfGlobalConfigData");
doNothing().when(spyGlobalConfigurationService).initGlobalDataConfig(globalDataConfig);
assertEquals(listOfGlobalConfigData, spyGlobalConfigurationService.instantiateGlobalConfigData(json));
}
示例3: executeJsonPost
import net.sf.json.JSON; //導入依賴的package包/類
public String executeJsonPost(String url, JSON jsonObj) throws ParseException, IOException
{
if(url.startsWith("/"))
{
url = host + url;
}
HttpPost post = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
post.setEntity(entity);
return fetchReponseText(post);
}
示例4: xml2ArrayForObject
import net.sf.json.JSON; //導入依賴的package包/類
/**
* 將xml中列表信息轉化對象數組
*
* @param xml
* @param beanClass
* @return
*/
public static Object[] xml2ArrayForObject(String xml, Class beanClass) {
// 設置root為數組
xml = setXmlRootAttrToArray(xml);
XMLSerializer xmlSer = new XMLSerializer();
JSON jsonArr = xmlSer.read(xml);
Object[] objArr = new Object[jsonArr.size()];
for (int i = 0; i < jsonArr.size(); i++) {
objArr[i] = JSONObject.toBean(
((JSONArray) jsonArr).getJSONObject(i), beanClass);
}
return objArr;
}
示例5: makeAPIRequest
import net.sf.json.JSON; //導入依賴的package包/類
public JSONObject makeAPIRequest(String apiFunction, @Nullable MultivaluedMap<String, String> params) {
ClientResponse clientResponse = makeAPIResource(apiFunction, params).get(ClientResponse.class);
log.info(clientResponse.getLocation());
String response = clientResponse.getEntity(String.class);
System.out.println(response);
log.info("response: " + response);
if (!method.equals("json/")) {
XMLSerializer xmlSerializer = new XMLSerializer();
JSON json = xmlSerializer.read(response);
System.out.println(json);
return JSONObject.fromObject(json);
} else
return JSONObject.fromObject(response);
}
示例6: testUnmarshalJSONObject
import net.sf.json.JSON; //導入依賴的package包/類
@Test
public void testUnmarshalJSONObject() throws Exception {
InputStream inStream = getClass().getResourceAsStream("testMessage1.json");
String in = context.getTypeConverter().convertTo(String.class, inStream);
JSON json = JSONSerializer.toJSON(in);
MockEndpoint mockXML = getMockEndpoint("mock:xml");
mockXML.expectedMessageCount(1);
mockXML.message(0).body().isInstanceOf(String.class);
Object marshalled = template.requestBody("direct:unmarshal", json);
Document document = context.getTypeConverter().convertTo(Document.class, marshalled);
assertEquals("The XML document has an unexpected root node", "o", document.getDocumentElement().getLocalName());
mockXML.assertIsSatisfied();
}
示例7: getParentCoverage
import net.sf.json.JSON; //導入依賴的package包/類
public CodeCoverageMetrics getParentCoverage(String sha) {
if (sha == null) {
return null;
}
try {
String coverageJSON = getCoverage(sha);
JsonSlurper jsonParser = new JsonSlurper();
JSON responseJSON = jsonParser.parseText(coverageJSON);
if (responseJSON instanceof JSONNull) {
return null;
}
JSONObject coverage = (JSONObject) responseJSON;
return new CodeCoverageMetrics(
((Double) coverage.getDouble(PACKAGE_COVERAGE_KEY)).floatValue(),
((Double) coverage.getDouble(FILES_COVERAGE_KEY)).floatValue(),
((Double) coverage.getDouble(CLASSES_COVERAGE_KEY)).floatValue(),
((Double) coverage.getDouble(METHOD_COVERAGE_KEY)).floatValue(),
((Double) coverage.getDouble(LINE_COVERAGE_KEY)).floatValue(),
((Double) coverage.getDouble(CONDITIONAL_COVERAGE_KEY)).floatValue());
} catch (Exception e) {
e.printStackTrace(logger.getStream());
}
return null;
}
示例8: requestJSON
import net.sf.json.JSON; //導入依賴的package包/類
/**
* Return the JSON data object from the URL.
*/
public Vertex requestJSON(String url, String attribute, Map<String, String> headers, Network network) {
log("GET JSON", Level.INFO, url, attribute);
try {
String json = Utils.httpGET(url, headers);
log("JSON", Level.FINE, json);
JSON root = (JSON)JSONSerializer.toJSON(json.trim());
if (root == null) {
return null;
}
Object value = root;
if (attribute != null) {
value = ((JSONObject)root).get(attribute);
if (value == null) {
return null;
}
}
Vertex object = convertElement(value, network);
return object;
} catch (Exception exception) {
log(exception);
return null;
}
}
示例9: processQuery
import net.sf.json.JSON; //導入依賴的package包/類
/**
* Process the mql query and convert the result to a JSON object.
*/
public JSON processQuery(String query) throws IOException {
log("MQL", Level.FINEST, query);
URL get = null;
if (KEY.isEmpty()) {
get = new URL(query);
} else {
get = new URL(query + "&key=" + KEY);
}
Reader reader = new InputStreamReader(get.openStream(), "UTF-8");
StringWriter output = new StringWriter();
int next = reader.read();
while (next != -1) {
output.write(next);
next = reader.read();
}
String result = output.toString();
log("JSON", Level.FINEST, result);
return JSONSerializer.toJSON(result);
}
示例10: newAccessToken
import net.sf.json.JSON; //導入依賴的package包/類
public String newAccessToken() {
try {
Map<String, String> params = new HashMap<String, String>();
params.put("refresh_token", this.refreshToken);
params.put("client_id", CLIENTID);
params.put("client_secret", CLIENTSECRET);
//params.put("redirect_uri", "urn:ietf:wg:oauth:2.0:oob");
params.put("grant_type", "refresh_token");
String json = Utils.httpPOST("https://accounts.google.com/o/oauth2/token", params);
JSON root = (JSON)JSONSerializer.toJSON(json);
if (!(root instanceof JSONObject)) {
return null;
}
return ((JSONObject)root).getString("access_token");
} catch (Exception exception) {
log(exception);
return null;
}
}
示例11: parseAndEncode
import net.sf.json.JSON; //導入依賴的package包/類
private void parseAndEncode(String name) throws IOException {
String msg = IOUtils.toString(XmlParser.class.getResourceAsStream(name));
ourLog.info(msg);
IParser p = ourCtx.newJsonParser();
Profile res = p.parseResource(Profile.class, msg);
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(res);
ourLog.info(encoded);
JSON expected = JSONSerializer.toJSON(msg.trim());
JSON actual = JSONSerializer.toJSON(encoded.trim());
String exp = expected.toString().replace("\\r\\n", "\\n"); // .replace("§", "§");
String act = actual.toString().replace("\\r\\n", "\\n");
ourLog.info("Expected: {}", exp);
ourLog.info("Actual : {}", act);
assertEquals(exp, act);
}
示例12: parseAndEncode
import net.sf.json.JSON; //導入依賴的package包/類
private void parseAndEncode(String name) throws IOException {
String msg = IOUtils.toString(XmlParser.class.getResourceAsStream(name), StandardCharsets.UTF_8);
// ourLog.info(msg);
msg = msg.replace("\"div\": \"<div>", "\"div\":\"<div xmlns=\\\"http://www.w3.org/1999/xhtml\\\">");
IParser p = ourCtx.newJsonParser();
Profile res = p.parseResource(Profile.class, msg);
String encoded = ourCtx.newJsonParser().setPrettyPrint(true).encodeResourceToString(res);
// ourLog.info(encoded);
JSON expected = JSONSerializer.toJSON(msg.trim());
JSON actual = JSONSerializer.toJSON(encoded.trim());
String exp = expected.toString().replace("\\r\\n", "\\n"); // .replace("§", "§");
String act = actual.toString().replace("\\r\\n", "\\n");
ourLog.info("Expected: {}", exp);
ourLog.info("Actual : {}", act);
assertEquals(exp, act);
}
示例13: addRowData
import net.sf.json.JSON; //導入依賴的package包/類
private Object[] addRowData(Object[] r) throws KettleException
{
// Parsing field
final JSON json = JSONSerializer.toJSON(r[data.fieldPos].toString());
final JXPathContext context = JXPathContext.newContext(json);
final String[] fieldNames = meta.getFieldName();
final RowMetaInterface rowMeta = data.outputRowMeta;
// Parsing each path into otuput rows
for (int i = 0; i < fieldNames.length; i++) {
final String fieldPath = meta.getXPath()[i];
final String fieldName = meta.getFieldName()[i];
final Object fieldValue = context.getValue(fieldPath);
final Integer fieldIndex = rowMeta.indexOfValue(fieldNames[i]);
final ValueMetaInterface valueMeta = rowMeta.getValueMeta(fieldIndex);
final DateFormat df = (valueMeta.getType() == ValueMetaInterface.TYPE_DATE)
? new SimpleDateFormat(meta.getFieldFormat()[i])
: null;
// safely add the unique field at the end of the output row
r = RowDataUtil.addValueData(r, fieldIndex, getRowDataValue(fieldName, valueMeta, valueMeta, fieldValue, df));
}
return r;
}
示例14: parseListFromData
import net.sf.json.JSON; //導入依賴的package包/類
/**
* Parses raw JSON data and returns the found strings.
*
* @param jsonName Name of attribute which is needed.
* @param data Contains raw JSON data.
* @return List of strings which were found by jsonName.
*/
private List<String> parseListFromData(String jsonName, String data) {
final List<String> result = new ArrayList<String>();
final JSON json = JSONSerializer.toJSON(data);
final Object jsonObject = ((JSONObject)json).get(jsonName);
if (JSONUtils.isArray(jsonObject)) {
Collection<String> jsonPaths = JSONArray.toCollection((JSONArray)jsonObject, String.class);
for (String jsonPath : jsonPaths) {
result.add(trimJSONPath(jsonPath));
}
} else {
result.add(trimJSONPath(String.valueOf(jsonObject)));
}
return result;
}
示例15: getValueFromJSONString
import net.sf.json.JSON; //導入依賴的package包/類
/**
* Returns the value of a key from a given JSON String.
*
* @param key Key to search after.
* @param jsonString Given JSON String, in which the key should be in.
* @return The value of the key in the JSON string.
*/
public static ArrayList<String> getValueFromJSONString(String key, String jsonString) {
final ArrayList<String> result = new ArrayList<String>();
LOG.info("JSON STRING: " + jsonString);
final JSON json = JSONSerializer.toJSON(jsonString);
final Object jsonObject = ((JSONObject)json).get(key);
if (JSONUtils.isArray(jsonObject)) {
Collection<String> jsonPaths = JSONArray.toCollection((JSONArray)jsonObject, String.class);
for (String jsonPath : jsonPaths) {
result.add(trimJSONSlashes(jsonPath));
}
} else {
if (!String.valueOf(jsonObject).equals("null")) {
result.add(CCRUtils.trimJSONSlashes(String.valueOf(jsonObject)));
}
}
return result;
}