本文整理汇总了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;
}
示例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();
}
示例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;
}
示例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.");
}
}
示例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);
}
}
示例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());
}
示例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);
}
示例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
}
示例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);
}
}
示例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;
}
示例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));
}
示例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;
}
}
示例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;
}
示例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();
}
示例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;
}