當前位置: 首頁>>代碼示例>>Java>>正文


Java JSON類代碼示例

本文整理匯總了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;
}
 
開發者ID:Blazemeter,項目名稱:jmeter-bzm-plugins,代碼行數:19,代碼來源:BlazeMeterHttpUtils.java

示例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));
}
 
開發者ID:jenkinsci,項目名稱:sonar-quality-gates-plugin,代碼行數:9,代碼來源:GlobalConfigurationServiceTest.java

示例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);
}
 
開發者ID:LinuxSuRen,項目名稱:phoenix.interface.framework,代碼行數:17,代碼來源:SimpleHttpClient.java

示例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;
}
 
開發者ID:thinking-github,項目名稱:nbone,代碼行數:23,代碼來源:JSONXOperUtils.java

示例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);
}
 
開發者ID:major2015,項目名稱:easyrec_major,代碼行數:21,代碼來源:AbstractApiTest.java

示例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();
}
 
開發者ID:HydAu,項目名稱:Camel,代碼行數:17,代碼來源:XmlJsonDataFormatTest.java

示例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;
}
 
開發者ID:uber,項目名稱:phabricator-jenkins-plugin,代碼行數:27,代碼來源:UberallsClient.java

示例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;
	}
}
 
開發者ID:BotLibre,項目名稱:BotLibre,代碼行數:27,代碼來源:Http.java

示例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);
}
 
開發者ID:BotLibre,項目名稱:BotLibre,代碼行數:23,代碼來源:Freebase.java

示例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;
	}
}
 
開發者ID:BotLibre,項目名稱:BotLibre,代碼行數:20,代碼來源:Google.java

示例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("&sect;", "§");
	String act = actual.toString().replace("\\r\\n", "\\n");

	ourLog.info("Expected: {}", exp);
	ourLog.info("Actual  : {}", act);

	assertEquals(exp, act);
}
 
開發者ID:gajen0981,項目名稱:FHIR-Server,代碼行數:22,代碼來源:JsonParserTest.java

示例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("&sect;", "§");
	String act = actual.toString().replace("\\r\\n", "\\n");

	ourLog.info("Expected: {}", exp);
	ourLog.info("Actual  : {}", act);

	assertEquals(exp, act);
}
 
開發者ID:jamesagnew,項目名稱:hapi-fhir,代碼行數:24,代碼來源:JsonParserTest.java

示例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;
}
 
開發者ID:instaclick,項目名稱:pdi-plugin-parsejsonstring,代碼行數:26,代碼來源:ParseJsonString.java

示例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;
}
 
開發者ID:ederst,項目名稱:ccr-parameter-plugin,代碼行數:23,代碼來源:CacheManager.java

示例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;
}
 
開發者ID:ederst,項目名稱:ccr-parameter-plugin,代碼行數:26,代碼來源:CCRUtils.java


注:本文中的net.sf.json.JSON類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。