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


Java JSONTokener類代碼示例

本文整理匯總了Java中org.json.JSONTokener的典型用法代碼示例。如果您正苦於以下問題:Java JSONTokener類的具體用法?Java JSONTokener怎麽用?Java JSONTokener使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


JSONTokener類屬於org.json包,在下文中一共展示了JSONTokener類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: getServiceAccountProjectId

import org.json.JSONTokener; //導入依賴的package包/類
public static String getServiceAccountProjectId(String credentialsPath)
{
	String project = null;
	if (credentialsPath != null)
	{
		try (InputStream credentialsStream = new FileInputStream(credentialsPath))
		{
			JSONObject json = new JSONObject(new JSONTokener(credentialsStream));
			project = json.getString("project_id");
		}
		catch (IOException | JSONException ex)
		{
			// ignore
		}
	}
	return project;
}
 
開發者ID:olavloite,項目名稱:spanner-jdbc,代碼行數:18,代碼來源:CloudSpannerConnection.java

示例2: parseIatResult

import org.json.JSONTokener; //導入依賴的package包/類
public static String parseIatResult(String json) {
		StringBuffer ret = new StringBuffer();
		try {
			JSONTokener tokener = new JSONTokener(json);
			JSONObject joResult = new JSONObject(tokener);

			JSONArray words = joResult.getJSONArray("ws");
			for (int i = 0; i < words.length(); i++) {
				// 轉寫結果詞,默認使用第一個結果
				JSONArray items = words.getJSONObject(i).getJSONArray("cw");
				JSONObject obj = items.getJSONObject(0);
				ret.append(obj.getString("w"));
//				如果需要多候選結果,解析數組其他字段
//				for(int j = 0; j < items.length(); j++)
//				{
//					JSONObject obj = items.getJSONObject(j);
//					ret.append(obj.getString("w"));
//				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return ret.toString();
	}
 
開發者ID:iPanelkegy,項目名稱:MobileMedia,代碼行數:25,代碼來源:JsonParser.java

示例3: createResponsesFromString

import org.json.JSONTokener; //導入依賴的package包/類
static List<Response> createResponsesFromString(String responseString, HttpURLConnection connection,
        RequestBatch requests, boolean isFromCache) throws FacebookException, JSONException, IOException {
    JSONTokener tokener = new JSONTokener(responseString);
    Object resultObject = tokener.nextValue();

    List<Response> responses = createResponsesFromObject(connection, requests, resultObject, isFromCache);
    Logger.log(LoggingBehavior.REQUESTS, RESPONSE_LOG_TAG, "Response\n  Id: %s\n  Size: %d\n  Responses:\n%s\n",
            requests.getId(), responseString.length(), responses);

    return responses;
}
 
開發者ID:MobileDev418,項目名稱:AndroidBackendlessChat,代碼行數:12,代碼來源:Response.java

示例4: getObjectFromJson

import org.json.JSONTokener; //導入依賴的package包/類
public static Object getObjectFromJson(String jsonString) throws JSONException {
    if ((jsonString == null) || jsonString.equals("")) {
    // We'd like the empty string to decode to the empty string.  Form.java
    // relies on this for the case where there's an activity result with no intent data.
    // We handle this case explicitly since nextValue() appears to throw an error
    // when given the empty string.
    return "";
  } else {
    final Object value = (new JSONTokener(jsonString)).nextValue();
    // Note that the JSONTokener may return a value equals() to null.
    if (value == null || value.equals(null)) {
      return null;
    } else if ((value instanceof String) ||
        (value instanceof Number) ||
        (value instanceof Boolean)) {
      return value;
    } else if (value instanceof JSONArray) {
      return getListFromJsonArray((JSONArray)value);
    } else if (value instanceof JSONObject) {
      return getListFromJsonObject((JSONObject)value);
    }
    throw new JSONException("Invalid JSON string.");
  }
}
 
開發者ID:mit-cml,項目名稱:appinventor-extensions,代碼行數:25,代碼來源:JsonUtil.java

示例5: onPostExecute

import org.json.JSONTokener; //導入依賴的package包/類
protected void onPostExecute(String response) {

            if (response == null) {
                response = "THERE WAS AN ERROR";
                forex = Long.parseLong("1");
            }
            else {
                try {
                    JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
                    JSONObject rates = object.getJSONObject("rates");
                    forex = rates.getLong("INR");

                    System.out.println("Rates " + rates);
                    System.out.println("Forex Rate:" + forex);


                } catch (JSONException e) {
                    // Appropriate error handling code
                    Log.e("Error", e.getMessage());
                }
                Log.i("INFO", response);
            }

        }
 
開發者ID:someaditya,項目名稱:CoinPryc,代碼行數:25,代碼來源:SecondActivity.java

示例6: testValidUpload_ExtModuleOnly

import org.json.JSONTokener; //導入依賴的package包/類
public void testValidUpload_ExtModuleOnly() throws Exception
{
    File zipFile = getResourceFile("validExtModule.zip");
    PostRequest postRequest = buildMultipartPostRequest(zipFile);

    AuthenticationUtil.setFullyAuthenticatedUser(NON_ADMIN_USER);
    Response response = sendRequest(postRequest, 403);

    AuthenticationUtil.setFullyAuthenticatedUser(CUSTOM_MODEL_ADMIN);
    response = sendRequest(postRequest, 200);

    JSONObject json = new JSONObject(new JSONTokener(response.getContentAsString()));
    assertFalse(json.has("modelName"));

    String extModule = json.getString("shareExtModule");
    Document document = XMLUtil.parse(extModule);
    NodeList nodes = document.getElementsByTagName("id");
    assertEquals(1, nodes.getLength());
    assertNotNull(nodes.item(0).getTextContent());
}
 
開發者ID:Alfresco,項目名稱:alfresco-remote-api,代碼行數:21,代碼來源:CustomModelImportTest.java

示例7: onPostExecute

import org.json.JSONTokener; //導入依賴的package包/類
protected void onPostExecute(String response) {

            if (response == null) {
                response = "THERE WAS AN ERROR";
            }
            try {
                JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
                JSONObject rates = object.getJSONObject("rates");
                forex = rates.getLong("INR");

                System.out.println("Rates " + rates);
                System.out.println("Forex Rate:" + forex);


            } catch (JSONException e) {
                // Appropriate error handling code
                Log.e("Error", e.getMessage());
            }
            Log.i("INFO", response);

        }
 
開發者ID:someaditya,項目名稱:CoinPryc,代碼行數:22,代碼來源:ThirdActivity.java

示例8: testValidUpload_ModelOnly

import org.json.JSONTokener; //導入依賴的package包/類
public void testValidUpload_ModelOnly() throws Exception
{
    File zipFile = getResourceFile("validModel.zip");
    PostRequest postRequest = buildMultipartPostRequest(zipFile);

    AuthenticationUtil.setFullyAuthenticatedUser(NON_ADMIN_USER);
    Response response = sendRequest(postRequest, 403);

    AuthenticationUtil.setFullyAuthenticatedUser(CUSTOM_MODEL_ADMIN);
    response = sendRequest(postRequest, 200);

    JSONObject json = new JSONObject(new JSONTokener(response.getContentAsString()));
    String importedModelName = json.getString("modelName");
    importedModels.add(importedModelName);

    assertFalse(json.has("shareExtModule"));

    // Import the same model again
    sendRequest(postRequest, 409); // name conflict
}
 
開發者ID:Alfresco,項目名稱:alfresco-remote-api,代碼行數:21,代碼來源:CustomModelImportTest.java

示例9: verifyStackOverFlowAccount

import org.json.JSONTokener; //導入依賴的package包/類
public boolean verifyStackOverFlowAccount(@NotNull @NonNls String username) {
	try {
		String url = SOFApiRoot + String.format(
				"users?order=asc&min=%s&max=%s&sort=name&inname=%s&site=stackoverflow",
				username,
				username,
				username
		);
		HttpURLConnection conn = HttpURLConnection.class.cast(new URL(url).openConnection());
		if (conn.getResponseCode() != 200) return false;
		JSONTokener tokener = new JSONTokener(new GZIPInputStream(conn.getInputStream()));
		// note that it was compressed
		JSONObject object = JSONObject.class.cast(tokener.nextValue());
		conn.disconnect();
		return object.getJSONArray("items").length() != 0;
		// 特判一下吧還是。。昨晚查詢不存在用戶返回的是200 ...和一個json
		// 上麵打這段注釋的,沒注意到我判斷了返回的結果是否包含有效用戶嗎 =-= , bug 'fixed'
	} catch (IOException e) {
		throw new RuntimeException("unable to fetch data from stackoverflow", e);
	}
}
 
開發者ID:ProgramLeague,項目名稱:strictfp-back-end,代碼行數:22,代碼來源:VerifyAccount.java

示例10: getIndex

import org.json.JSONTokener; //導入依賴的package包/類
public static ElasticsearchClient getIndex() {
    if (index == null) {
        // create index
        String elasticsearchAddress = config.getOrDefault("grid.elasticsearch.address", "localhost:9300");
        String elasticsearchClusterName = config.getOrDefault("grid.elasticsearch.clusterName", "");
        String elasticsearchWebIndexName= config.getOrDefault("grid.elasticsearch.webIndexName", "web");
        Path webMappingPath = Paths.get("conf/mappings/web.json");
        if (webMappingPath.toFile().exists()) try {
            index = new ElasticsearchClient(new String[]{elasticsearchAddress}, elasticsearchClusterName.length() == 0 ? null : elasticsearchClusterName);
            index.createIndexIfNotExists(elasticsearchWebIndexName, 1 /*shards*/, 1 /*replicas*/);
            String mapping = new String(Files.readAllBytes(webMappingPath));
            JSONObject mo = new JSONObject(new JSONTokener(mapping));
            mo = mo.getJSONObject("mappings").getJSONObject("_default_");
            index.setMapping("web", mo.toString());
            Data.logger.info("Connected elasticsearch at " + getHost(elasticsearchAddress));
        } catch (IOException | NoNodeAvailableException e) {
            index = null; // index not available
            Data.logger.info("Failed connecting elasticsearch at " + getHost(elasticsearchAddress) + ": " + e.getMessage(), e);
        } else {
            Data.logger.info("no web index mapping available, no connection to elasticsearch attempted");
        }
    }
    return index;
}
 
開發者ID:yacy,項目名稱:yacy_grid_mcp,代碼行數:25,代碼來源:Data.java

示例11: testCopy

import org.json.JSONTokener; //導入依賴的package包/類
/**
 * This test verifies that copying a shared node does not across the shared aspect and it's associated properties.
 * @throws IOException 
 * @throws UnsupportedEncodingException 
 * @throws JSONException 
 * @throws FileNotFoundException 
 * @throws FileExistsException 
 */
public void testCopy() throws UnsupportedEncodingException, IOException, JSONException, FileExistsException, FileNotFoundException 
{
    final int expectedStatusOK = 200;
    
    String testNodeRef = testNode.toString().replace("://", "/");

    // As user one ...
    
    // share
    Response rsp = sendRequest(new PostRequest(SHARE_URL.replace("{node_ref_3}", testNodeRef), "", APPLICATION_JSON), expectedStatusOK, USER_ONE);
    JSONObject jsonRsp = new JSONObject(new JSONTokener(rsp.getContentAsString()));
    String sharedId = jsonRsp.getString("sharedId");
    assertNotNull(sharedId);
    assertEquals(22, sharedId.length()); // note: we may have to adjust/remove this check if we change length of id (or it becomes variable length)

    AuthenticationUtil.setFullyAuthenticatedUser(USER_ONE);
    FileInfo copyFileInfo = fileFolderService.copy(testNode, userOneHome, "Copied node");
    NodeRef copyNodeRef = copyFileInfo.getNodeRef();
    
    assertFalse(nodeService.hasAspect(copyNodeRef, QuickShareModel.ASPECT_QSHARE));
}
 
開發者ID:Alfresco,項目名稱:alfresco-remote-api,代碼行數:30,代碼來源:QuickShareRestApiTest.java

示例12: read

import org.json.JSONTokener; //導入依賴的package包/類
public static Bundle read( InputStream stream ) {
	
	try {
		BufferedReader reader = new BufferedReader( new InputStreamReader( stream ) );

		StringBuilder builder = new StringBuilder();

		char[] buffer = new char[0x2000];
		int count = reader.read( buffer );
		while (count > 0) {
			for (int i=0; i < count; i++) {
				buffer[i] ^= XOR_KEY;
			}
			builder.append( buffer, 0, count );
			count = reader.read( buffer );
		}
		
		JSONObject json = (JSONObject)new JSONTokener( builder.toString() ).nextValue();
		reader.close();
		
		return new Bundle( json );
	} catch (Exception e) {
		return null;
	}
}
 
開發者ID:kurtyu,項目名稱:PixelDungeonTC,代碼行數:26,代碼來源:Bundle.java

示例13: createResponsesFromString

import org.json.JSONTokener; //導入依賴的package包/類
static List<GraphResponse> createResponsesFromString(
        String responseString,
        HttpURLConnection connection,
        GraphRequestBatch requests
) throws FacebookException, JSONException, IOException {
    JSONTokener tokener = new JSONTokener(responseString);
    Object resultObject = tokener.nextValue();

    List<GraphResponse> responses = createResponsesFromObject(
            connection,
            requests,
            resultObject);
    Logger.log(
            LoggingBehavior.REQUESTS,
            RESPONSE_LOG_TAG,
            "Response\n  Id: %s\n  Size: %d\n  Responses:\n%s\n",
            requests.getId(),
            responseString.length(),
            responses);

    return responses;
}
 
開發者ID:eviltnan,項目名稱:kognitivo,代碼行數:23,代碼來源:GraphResponse.java

示例14: parseIatResult

import org.json.JSONTokener; //導入依賴的package包/類
public static String parseIatResult(String json) {
		if(json.startsWith("<"))return AudioXmlParser.parseXmlResult(json,0);
		StringBuffer ret = new StringBuffer();
		try {
			JSONTokener tokener = new JSONTokener(json);
			JSONObject joResult = new JSONObject(tokener);

			JSONArray words = joResult.getJSONArray("ws");
			for (int i = 0; i < words.length(); i++) {
				// 轉寫結果詞,默認使用第一個結�?
				JSONArray items = words.getJSONObject(i).getJSONArray("cw");
				JSONObject obj = items.getJSONObject(0);
				ret.append(obj.getString("w"));
//				如果�?��多�?選結果,解析數組其他字段
//				for(int j = 0; j < items.length(); j++)
//				{
//					JSONObject obj = items.getJSONObject(j);
//					ret.append(obj.getString("w"));
//				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return ret.toString();
	}
 
開發者ID:LingjuAI,項目名稱:AssistantBySDK,代碼行數:26,代碼來源:AudioJsonParser.java

示例15: mockResultset

import org.json.JSONTokener; //導入依賴的package包/類
private ResultSet mockResultset(List<Long> archivedNodes, List<Long> versionNodes) throws JSONException
{

    NodeService nodeService = mock(NodeService.class);
    when(nodeService.getNodeRef(any())).thenAnswer(new Answer<NodeRef>() {
        @Override
        public NodeRef answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            //If the DBID is in the list archivedNodes, instead of returning a noderef return achivestore noderef
            if (archivedNodes.contains(args[0])) return new NodeRef(StoreRef.STORE_REF_ARCHIVE_SPACESSTORE, GUID.generate());
            if (versionNodes.contains(args[0])) return new NodeRef(StoreMapper.STORE_REF_VERSION2_SPACESSTORE, GUID.generate()+args[0]);
            return new NodeRef(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE, GUID.generate());
        }
    });

    SearchParameters sp = new SearchParameters();
    sp.setBulkFetchEnabled(false);
    JSONObject json = new JSONObject(new JSONTokener(JSON_REPONSE));
    ResultSet results = new SolrJSONResultSet(json,sp,nodeService, null, LimitBy.FINAL_SIZE, 10);
    return results;
}
 
開發者ID:Alfresco,項目名稱:alfresco-remote-api,代碼行數:22,代碼來源:ResultMapperTests.java


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