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


Java JSONObject.opt方法代碼示例

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


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

示例1: init

import org.json.JSONObject; //導入方法依賴的package包/類
public void init (FirebaseApp firebaseApp) {
	mFirebaseApp = firebaseApp;
	String token = getFirebaseMessagingToken();

	dispatcher =
	new FirebaseJobDispatcher(new GooglePlayDriver(activity.getApplicationContext()));
	dispatcher.cancel("firebase-notify-in-time-UID");

	Utils.d("Firebase Cloud messaging token: " + token);

	// Perform task here..!
	if (KeyValueStorage.getValue("notification_complete_task") != "0") {
		try {
			JSONObject obj =
			new JSONObject(KeyValueStorage.getValue("notification_task_data"));

			Dictionary data = new Dictionary();
			Iterator<String> iterator = obj.keys();

			while (iterator.hasNext()) {
				String key = iterator.next();
				Object value = obj.opt(key);

				if (value != null) {
					data.put(key, value);
				}
			}

			Utils.callScriptCallback(
			KeyValueStorage.getValue("notification_complete_task"),
			"Notification", "TaskComplete", data);

		} catch (JSONException e) {

		}

		KeyValueStorage.setValue("notification_complete_task", "0");
	}
}
 
開發者ID:FrogSquare,項目名稱:GodotFireBase,代碼行數:40,代碼來源:Notification.java

示例2: getChecksFromJson

import org.json.JSONObject; //導入方法依賴的package包/類
/**
 * Gets a list of connection checks from JSON. If json does not contain a 'check' field
 * null will be returned instead.
 *
 * @param json The JSON to extract the connection checks from.
 * @param checksKey The key for the checks.
 *
 * @return The set of checks or null.
 */
@Nullable
public static String[] getChecksFromJson(JSONObject json, String checksKey) {
    Object checkObj = json.opt(checksKey);
    String[] checks = null;
    if (checkObj == null) {
        // Do nothing, ignore other checks
    } else if (checkObj instanceof JSONArray) {
        JSONArray jsonChecks = (JSONArray) checkObj;
        if (jsonChecks != null) {
            int count = jsonChecks.length();
            checks = new String[count];
            for (int i = 0; i < count; i++) {
                checks[i] = jsonChecks.optString(i);
                if (checks[i] == null) {
                    throw new IllegalArgumentException("Malformatted check array in Input.");
                }
            }
        }
    } else if (checkObj instanceof String) {
        checks = new String[]{(String) checkObj};
    }
    return checks;
}
 
開發者ID:Axe-Ishmael,項目名稱:Blockly,代碼行數:33,代碼來源:Input.java

示例3: loadFromJSON

import org.json.JSONObject; //導入方法依賴的package包/類
private void loadFromJSON(JSONObject json) throws JSONException {
  // Get the status code
  this.statusCode = (String) json.get(JsonTagsZ.STATUS);
  if (JsonTagsZ.STATUS_TRUE.equals(this.statusCode)) {
    this.status = true;
  } else {
    this.status = false;
  }

  if (!status) {
    this.errMsg = (String) json.opt(JsonTagsZ.MESSAGE);
    this.errors = getErrorData(json);
  } else {
    // Load the userId
    this.userId = (String) json.get(JsonTagsZ.USER_ID);
    // Load the kiosk Id
    this.entityId = (String) json.get(JsonTagsZ.KIOSK_ID);
  }
}
 
開發者ID:logistimo,項目名稱:logistimo-web-service,代碼行數:20,代碼來源:SetupDataOutput.java

示例4: handle

import org.json.JSONObject; //導入方法依賴的package包/類
@Override
public Response handle() throws Exception {
  WebDriverLikeCommand command =
      WebDriverLikeCommand.valueOf(getRequest().getVariableValue(":command"));
  JSONObject payload = JavaxJson.toOrgJson(getRequest().getPayload());

  @SuppressWarnings("unchecked")
  Iterator<String> iter = payload.keys();
  while (iter.hasNext()) {
    String key = iter.next();
    Object value = payload.opt(key);
    getSession().configure(command).set(key, value);
  }

  Response resp = new Response();
  resp.setSessionId(getSession().getSessionId());
  resp.setStatus(0);
  resp.setValue(new JSONObject());
  return resp;

}
 
開發者ID:google,項目名稱:devtools-driver,代碼行數:22,代碼來源:SetConfigurationHandler.java

示例5: parseJson_should_return_correct_testclass_object

import org.json.JSONObject; //導入方法依賴的package包/類
@Test
public void parseJson_should_return_correct_testclass_object()
        throws StockException {
    String jsonString = "{  \"id\":1234,  \"description\":\"Sample description\", \"property\": {     \"key\": \"test key\"  },  \"array\":[3,5,9,10],  \"required\":true,  \"precision\":10.12}";
    JSONObject testObj = new JSONObject(jsonString);
    TestClass parsedObj = (TestClass) JsonUtils.parseJson(TestClass.class,
            jsonString);

    Assert.assertEquals(testObj.opt("id"), checkNull(parsedObj.getId()));
    Assert.assertEquals(testObj.opt("description"),
            checkNull(parsedObj.getDescription()));
    Assert.assertEquals(testObj.opt("required"),
            checkNull(parsedObj.getRequired()));

    if (!testObj.isNull("array")) {
        JSONArray objArray = (JSONArray) testObj.opt("array");
        ArrayList<Integer> parsedArray = parsedObj.getArray();
        for (int i = 0; i < objArray.length(); i++) {
            Assert.assertTrue(parsedArray.contains(objArray.get(i)));
        }
    }
    if (!testObj.isNull("property")) {
        JSONObject obj = (JSONObject) testObj.opt("property");
        Assert.assertNotNull(parsedObj.getProperty());
        Assert.assertEquals(checkNull(obj.opt("key")),
                parsedObj.getProperty().getKey());

    }
}
 
開發者ID:adobe,項目名稱:stock-api-sdk,代碼行數:30,代碼來源:JsonUtilsTest.java

示例6: jsonObjectContainsValue

import org.json.JSONObject; //導入方法依賴的package包/類
static boolean jsonObjectContainsValue(JSONObject jsonObject, Object value) {
    @SuppressWarnings("unchecked")
    Iterator<String> keys = (Iterator<String>) jsonObject.keys();
    while (keys.hasNext()) {
        Object thisValue = jsonObject.opt(keys.next());
        if (thisValue != null && thisValue.equals(value)) {
            return true;
        }
    }
    return false;
}
 
開發者ID:MobileDev418,項目名稱:chat-sdk-android-push-firebase,代碼行數:12,代碼來源:JsonUtil.java

示例7: getParameterValueDict

import org.json.JSONObject; //導入方法依賴的package包/類
/**
 * Convert a JSONObject into a HashMap
 */
static HashMap<String, ParameterValue> getParameterValueDict(JSONObject json) {
    Iterator<String> keys = json.keys();
    HashMap<String, ParameterValue> dict = new HashMap<>();
    while (keys.hasNext()) {
        String key = keys.next();
        Object p = json.opt(key);
        if (p != null) {
            ParameterValue param = new ParameterValue(p);
            dict.put(key, param);
        }
    }
    return dict;
}
 
開發者ID:pullstring,項目名稱:pullstring-android,代碼行數:17,代碼來源:ParameterValue.java

示例8: FetchUpdateOptions

import org.json.JSONObject; //導入方法依賴的package包/類
@SuppressWarnings("unchecked")
public FetchUpdateOptions(final JSONObject json) throws JSONException {
    if (json == null) {
        throw new JSONException("Can't parse null json object");
    }

    this.configURL = json.optString(CONFIG_URL_JSON_KEY, null);

    final JSONObject requestHeadersJson = (JSONObject) json.opt(REQUEST_HEADERS_JSON_KEY);
    if (requestHeadersJson != null) {
        this.requestHeaders = JSONUtils.toFlatStringMap(requestHeadersJson);
    }
}
 
開發者ID:SUTFutureCoder,項目名稱:localcloud_fe,代碼行數:14,代碼來源:FetchUpdateOptions.java

示例9: getCategory

import org.json.JSONObject; //導入方法依賴的package包/類
/**
 * Gets a category by the specified request.
 * <p>
 * Renders the response with a json object, for example,
 * 
 * <pre>
 * {
 *     "sc": boolean,
 *     "category": {
 *         "oId": "",
 *         "categoryTitle": "",
 *         "categoryURI": "",
 *         ....
 *     }
 * }
 * </pre>
 * </p>
 *
 * @param request
 *            the specified http servlet request
 * @param response
 *            the specified http servlet response
 * @param context
 *            the specified http request context
 * @throws Exception
 *             exception
 */
@RequestMapping(value = "/console/category/*", method = RequestMethod.GET)
public void getCategory(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
	if (!userQueryService.isAdminLoggedIn(request)) {
		response.sendError(HttpServletResponse.SC_FORBIDDEN);
		return;
	}

	final JSONRenderer renderer = new JSONRenderer();

	try {
		final String requestURI = request.getRequestURI();
		final String categoryId = requestURI.substring((Latkes.getContextPath() + "/console/category/").length());

		final JSONObject result = categoryQueryService.getCategory(categoryId);
		if (null == result) {
			renderer.setJSONObject(QueryResults.defaultResult());
			renderer.render(request, response);
			return;
		}

		final StringBuilder tagBuilder = new StringBuilder();
		final List<JSONObject> tags = (List<JSONObject>) result.opt(Category.CATEGORY_T_TAGS);
		for (final JSONObject tag : tags) {
			tagBuilder.append(tag.optString(Tag.TAG_TITLE)).append(",");
		}
		tagBuilder.deleteCharAt(tagBuilder.length() - 1);
		result.put(Category.CATEGORY_T_TAGS, tagBuilder.toString());

		renderer.setJSONObject(result);
		result.put(Keys.STATUS_CODE, true);
	} catch (final ServiceException e) {
		logger.error(e.getMessage(), e);

		final JSONObject jsonObject = QueryResults.defaultResult();
		renderer.setJSONObject(jsonObject);
		jsonObject.put(Keys.MSG, langPropsService.get("getFailLabel"));
	}
	renderer.render(request, response);
}
 
開發者ID:daima,項目名稱:solo-spring,代碼行數:67,代碼來源:CategoryConsole.java

示例10: getPreviousArticle

import org.json.JSONObject; //導入方法依賴的package包/類
public JSONObject getPreviousArticle(final String articleId) throws RepositoryException {
	final JSONObject currentArticle = get(articleId);
	final Date currentArticleCreateDate = (Date) currentArticle.opt(Article.ARTICLE_CREATE_DATE);

	final Query query = new Query()
			.setFilter(CompositeFilterOperator.and(
					new PropertyFilter(Article.ARTICLE_CREATE_DATE, FilterOperator.LESS_THAN,
							currentArticleCreateDate),
					new PropertyFilter(Article.ARTICLE_IS_PUBLISHED, FilterOperator.EQUAL, true)))
			.addSort(Article.ARTICLE_CREATE_DATE, SortDirection.DESCENDING).setCurrentPageNum(1).setPageSize(1)
			.setPageCount(1).addProjection(Article.ARTICLE_TITLE, String.class)
			.addProjection(Article.ARTICLE_PERMALINK, String.class)
			.addProjection(Article.ARTICLE_ABSTRACT, String.class);

	final JSONObject result = get(query);
	final JSONArray array = result.optJSONArray(Keys.RESULTS);

	if (1 != array.length()) {
		return null;
	}

	final JSONObject ret = new JSONObject();
	final JSONObject article = array.optJSONObject(0);

	try {
		ret.put(Article.ARTICLE_TITLE, article.getString(Article.ARTICLE_TITLE));
		ret.put(Article.ARTICLE_PERMALINK, article.getString(Article.ARTICLE_PERMALINK));
		ret.put(Article.ARTICLE_ABSTRACT, article.getString((Article.ARTICLE_ABSTRACT)));
	} catch (final JSONException e) {
		throw new RepositoryException(e);
	}

	return ret;
}
 
開發者ID:daima,項目名稱:solo-spring,代碼行數:35,代碼來源:ArticleDao.java

示例11: getErrorData

import org.json.JSONObject; //導入方法依賴的package包/類
private Vector getErrorData(JSONObject json) throws JSONException {
  Vector errors = new Vector();
  JSONArray array = (JSONArray) json.opt(JsonTagsZ.ERRORS);
  for (int i = 0; i < array.length(); i++) {
    String e = (String) array.get(i);
    // Add to vector
    errors.addElement(e.toString());
  }
  return errors;
}
 
開發者ID:logistimo,項目名稱:logistimo-web-service,代碼行數:11,代碼來源:SetupDataOutput.java

示例12: getValue

import org.json.JSONObject; //導入方法依賴的package包/類
@SuppressWarnings("unchecked") public <T> T getValue(String section, String property, T defaultValue) {
    JSONObject oSection = getSection(section);
    Object value = oSection.opt(property);
    if (value == null) {
        return defaultValue;
    }
    return (T) value;
}
 
開發者ID:jalian-systems,項目名稱:marathonv5,代碼行數:9,代碼來源:AbstractPreferences.java

示例13: createAnimatablePathOrSplitDimensionPath

import org.json.JSONObject; //導入方法依賴的package包/類
static AnimatableValue<PointF> createAnimatablePathOrSplitDimensionPath(
    JSONObject json, LottieComposition composition) {
  if (json.has("k")) {
    return new AnimatablePathValue(json.opt("k"), composition);
  } else {
    return new AnimatableSplitDimensionPathValue(
        AnimatableFloatValue.Factory.newInstance(json.optJSONObject("x"), composition),
        AnimatableFloatValue.Factory.newInstance(json.optJSONObject("y"), composition));
  }
}
 
開發者ID:alibaba,項目名稱:atlas,代碼行數:11,代碼來源:AnimatablePathValue.java

示例14: jsonObjectEntrySet

import org.json.JSONObject; //導入方法依賴的package包/類
static Set<Map.Entry<String, Object>> jsonObjectEntrySet(JSONObject jsonObject) {
    HashSet<Map.Entry<String, Object>> result = new HashSet<Map.Entry<String, Object>>();

    @SuppressWarnings("unchecked")
    Iterator<String> keys = (Iterator<String>) jsonObject.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        Object value = jsonObject.opt(key);
        result.add(new JSONObjectEntry(key, value));
    }

    return result;
}
 
開發者ID:MobileDev418,項目名稱:AndroidBackendlessChat,代碼行數:14,代碼來源:JsonUtil.java

示例15: getErrorData

import org.json.JSONObject; //導入方法依賴的package包/類
private Vector getErrorData(JSONObject json) throws JSONException {
  Vector errMsgs = new Vector();
  JSONArray array = (JSONArray) json.opt(JsonTagsZ.ERRORS);
  if (array != null) {
    for (int i = 0; i < array.length(); i++) {
      String e = (String) array.get(i);
      // Add to vector
      errMsgs.addElement(e.toString());
    }
  }
  return errMsgs;
}
 
開發者ID:logistimo,項目名稱:logistimo-web-service,代碼行數:13,代碼來源:BasicOutput.java


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