Java Code Examples for org.json.JSONObject#remove()

The following examples show how to use org.json.JSONObject#remove() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CastMessageHandler.java    From delion with Apache License 2.0 6 votes vote down vote up
/**
 * Remove 'null' fields from a JSONObject. This method calls itself recursively until all the
 * fields have been looked at.
 * TODO(mlamouri): move to some util class?
 */
private static void removeNullFields(Object object) throws JSONException {
    if (object instanceof JSONArray) {
        JSONArray array = (JSONArray) object;
        for (int i = 0; i < array.length(); ++i) removeNullFields(array.get(i));
    } else if (object instanceof JSONObject) {
        JSONObject json = (JSONObject) object;
        JSONArray names = json.names();
        if (names == null) return;
        for (int i = 0; i < names.length(); ++i) {
            String key = names.getString(i);
            if (json.isNull(key)) {
                json.remove(key);
            } else {
                removeNullFields(json.get(key));
            }
        }
    }
}
 
Example 2
Source File: SessionManager.java    From Angelia-core with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Wipes the {@link AuthenticationHandler} from the session manager
 * 
 * @param auth - The {@link AuthenticationHandler} to remove
 * 
 */
public synchronized void deleteAuth(AuthenticationHandler auth) {
	logger.info("Deleting access tokens for " + auth.getPlayerName() + " from save file");
	JSONObject json = loadAuthJson(saveFile);
	if (json == null) {
		return;
	}
	json.put("clientToken", clientToken);
	JSONObject authSection = json.optJSONObject("authenticationDatabase");
	if (authSection == null) {
		return;
	}
	String identifierString = legacyFormat ? auth.getPlayerUUID() : auth.getUserID();
	authSection.remove(identifierString);
	saveJSON(saveFile, json);
}
 
Example 3
Source File: VisaCheckoutNonceUnitTest.java    From braintree_android with MIT License 6 votes vote down vote up
@Test
public void fromJson_whenNoCallId_createsVisaCheckoutNonceWithEmptyCallId() throws JSONException {
    JSONObject visaCheckoutResponseJson = new JSONObject(stringFromFixture(
            "payment_methods/visa_checkout_response.json"));

    JSONArray visaCheckoutCardsJson = visaCheckoutResponseJson.getJSONArray("visaCheckoutCards");
    JSONObject visaCheckoutNonceJson = visaCheckoutCardsJson.getJSONObject(0);
    visaCheckoutNonceJson.remove("callId");

    visaCheckoutCardsJson.put(0, visaCheckoutNonceJson);
    visaCheckoutResponseJson.put("visaCheckoutCards", visaCheckoutCardsJson);

    VisaCheckoutNonce visaCheckoutNonce = VisaCheckoutNonce.fromJson(visaCheckoutResponseJson.toString());

    assertEquals("", visaCheckoutNonce.getCallId());
}
 
Example 4
Source File: ActivityInstance.java    From mdw with Apache License 2.0 6 votes vote down vote up
@Override
public JSONObject getSummaryJson(int detail) {
    JSONObject json = getSummaryJson();
    json.remove("name");
    if (detail > 0) {
        if (processId != null)
            json.put("processId", processId);
        if (name != null)
            json.put("activityName", name);
        if (processName != null)
            json.put("processName", processName);
        if (processVersion != null)
            json.put("processVersion", processVersion);
        if (packageName != null)
            json.put("packageName", packageName);
        if (processInstanceId != null)
            json.put("processInstanceId", processInstanceId);
    }
    if (detail > 1) {
        if (milestoneName != null)
            json.put("milestoneName", milestoneName);
        if (milestoneGroup != null)
            json.put("milestoneGroup", milestoneGroup);
    }
    return json;
}
 
Example 5
Source File: SimpleMetaStoreLiveMigrationTests.java    From orion.server with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * A user with no workspaces and does not have a version. This should never occur but test to reproduce corruption.
 * @throws Exception
 */
@Test
public void testUserWithNoWorkspacesNoVersion() throws Exception {
	// create metadata on disk
	testUserId = testName.getMethodName();
	JSONObject newUserJSON = createUserJson(SimpleMetaStore.VERSION, testUserId, EMPTY_LIST);
	newUserJSON.remove(SimpleMetaStore.ORION_VERSION);
	createUserMetaData(newUserJSON, testUserId);

	// since we modified files on disk directly, force user cache update by reading all users
	OrionConfiguration.getMetaStore().readAllUsers();

	// verify web requests
	verifyWorkspaceRequest(EMPTY_LIST);

	// verify metadata on disk
	verifyUserMetaData(testUserId, EMPTY_LIST);
}
 
Example 6
Source File: PluginManagerTest.java    From plugin-installation-manager-tool with MIT License 5 votes vote down vote up
@Test
public void getSecurityWarningsWhenNoWarningsTest() {
    JSONObject json = setTestUcJson();
    json.remove("warnings");
    assertFalse(json.has("warnings"));

    Map<String, List<SecurityWarning>> allSecurityWarnings = pm.getSecurityWarnings();

    assertEquals(0, allSecurityWarnings.size());
}
 
Example 7
Source File: DcosVersionTest.java    From dcos-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonContruction() {
    JSONObject j = new JSONObject();
    j.put(dcosVersionKey, testVersion);
    Assert.assertEquals(DcosVersion.DcosVariant.UNKNOWN, new DcosVersion(j).getDcosVariant());

    Assert.assertEquals(
            DcosVersion.DcosVariant.OPEN,
            new DcosVersion(
                    j.put(dcosVariantKey, DcosVersion.DcosVariant.OPEN.toString())
            ).getDcosVariant()
    );
    j.remove(dcosVariantKey);

    Assert.assertEquals(
            DcosVersion.DcosVariant.ENTERPRISE,
            new DcosVersion(
                    j.put(dcosVariantKey, DcosVersion.DcosVariant.ENTERPRISE.toString())
            ).getDcosVariant()
    );
    j.remove(dcosVariantKey);

    Assert.assertEquals(
            DcosVersion.DcosVariant.UNKNOWN,
            new DcosVersion(
                    j.put(dcosVariantKey, DcosVersion.DcosVariant.UNKNOWN.toString())
            ).getDcosVariant()
    );
    j.remove(dcosVariantKey);

    Assert.assertEquals(
            DcosVersion.DcosVariant.UNKNOWN,
            new DcosVersion(
                    j.put(dcosVariantKey, "DC/OS Enterprise")
            ).getDcosVariant()
    );
}
 
Example 8
Source File: EDSLocationBase.java    From edslite with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void saveToJSONObject(JSONObject jo) throws JSONException
{
	super.saveToJSONObject(jo);
	jo.put(SETTINGS_OPEN_READ_ONLY, shouldOpenReadOnly());
	if (_autoCloseTimeout > 0)
		jo.put(SETTINGS_AUTO_CLOSE_TIMEOUT, _autoCloseTimeout);
	else
		jo.remove(SETTINGS_AUTO_CLOSE_TIMEOUT);
}
 
Example 9
Source File: AbstractPreferences.java    From marathonv5 with Apache License 2.0 5 votes vote down vote up
public void setValue(String section, String property, Object value) {
    JSONObject oSection = getSection(section);
    if (value == null)
        oSection.remove(property);
    else
        oSection.put(property, value);
    save(section);
}
 
Example 10
Source File: StringSchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringNoFormat() {
    JSONObject rawSchemaJson = ResourceLoader.DEFAULT.readObj("tostring/stringschema.json");
    rawSchemaJson.remove("format");
    String actual = SchemaLoader.load(rawSchemaJson).toString();
    assertThat(new JSONObject(actual), sameJsonAs(rawSchemaJson));
}
 
Example 11
Source File: RuleServiceTest.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void testUpdateRule() throws Exception
{
    JSONObject jsonRule = createRule(testNodeRef);

    String ruleId = jsonRule.getJSONObject("data").getString("id");

    Response getResponse = sendRequest(new GetRequest(formateRuleUrl(testNodeRef, ruleId)), 200);

    JSONObject before = new JSONObject(getResponse.getContentAsString());

    // do some changes
    before.put("description", "this is modified description for test_rule");

    // do some changes for action object
    JSONObject beforeAction = before.getJSONObject("action");
    // no changes for actions list  
    beforeAction.remove("actions");
    // clear conditions
    beforeAction.put("conditions", new JSONArray());

    Response putResponse = sendRequest(new PutRequest(formateRuleUrl(testNodeRef, ruleId), before.toString(), "application/json"), 200);

    JSONObject after = new JSONObject(putResponse.getContentAsString());

    // sent and retrieved objects should be the same (except ids and urls)
    // this means that all changes was saved
    checkUpdatedRule(before, after);
}
 
Example 12
Source File: ConditionalSchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void toString_noIf() {
    ConditionalSchema subject = initCompleteSchema().ifSchema(null).build();
    JSONObject expectedSchemaJson = LOADER.readObj("conditionalschema.json");
    expectedSchemaJson.remove("if");

    JSONObject actual = new JSONObject(subject.toString());

    assertThat(actual, sameJsonAs(expectedSchemaJson));
}
 
Example 13
Source File: Single.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void loadSave(JSONObject save) {
    if (save.has("levelProgress")) {
        save.remove("levelProgress");
    }
    field.loadSave(save);
}
 
Example 14
Source File: WifiListFragment.java    From MobileInfo with Apache License 2.0 5 votes vote down vote up
public List<Param> getListParam(JSONArray jsonArray) {
    List<Param> list = new ArrayList<>();
    try {
        for (int i = 0; i < jsonArray.length(); i++) {
            Param param = new Param();
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            if (jsonObject.has("isSystem")) {
                if (!jsonObject.getBoolean("isSystem")) {
                    param.setValue(jsonObject.get("icon"));
                    jsonObject.remove("icon");
                    String key = StringUtil.formatString(jsonObject.toString());
                    param.setKey(key);
                    list.add(param);
                }
            } else {
                param.setKey(i + 1 + "");
                String value = StringUtil.formatString(jsonObject.toString());
                param.setValue(value);
                list.add(param);
            }

        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return list;
}
 
Example 15
Source File: ValidatorTest.java    From aws-cloudformation-resource-schema with Apache License 2.0 5 votes vote down vote up
/**
 * trivial coverage test: cannot cache a schema if it has no $id
 */
@Test
public void registerMetaSchema_nullId_shouldThrow() {
    JSONObject badSchema = loadJSON(RESOURCE_DEFINITION_SCHEMA_PATH);
    badSchema.remove("$id");
    assertThatExceptionOfType(ValidationException.class).isThrownBy(() -> {
        validator.registerMetaSchema(SchemaLoader.builder(), badSchema);
    });
}
 
Example 16
Source File: ObjectSchemaTest.java    From json-schema with Apache License 2.0 5 votes vote down vote up
@Test
public void toStringNoExplicitType() {
    JSONObject rawSchemaJson = loader.readObj("tostring/objectschema.json");
    rawSchemaJson.remove("type");
    String actual = SchemaLoader.load(rawSchemaJson).toString();
    assertThat(new JSONObject(actual), sameJsonAs(rawSchemaJson));
}
 
Example 17
Source File: SensorsDataAPI.java    From sa-sdk-android with Apache License 2.0 4 votes vote down vote up
private void trackItemEvent(String itemType, String itemId, String eventType, JSONObject properties) {
    try {
        assertKey(itemType);
        assertValue(itemId);
        assertPropertyTypes(properties);

        String eventProject = null;
        if (properties != null && properties.has("$project")) {
            eventProject = (String) properties.get("$project");
            properties.remove("$project");
        }

        JSONObject libProperties = new JSONObject();
        libProperties.put("$lib", "Android");
        libProperties.put("$lib_version", VERSION);
        libProperties.put("$lib_method", "code");

        if (mDeviceInfo.containsKey("$app_version")) {
            libProperties.put("$app_version", mDeviceInfo.get("$app_version"));
        }

        JSONObject superProperties = mSuperProperties.get();
        if (superProperties != null) {
            if (superProperties.has("$app_version")) {
                libProperties.put("$app_version", superProperties.get("$app_version"));
            }
        }

        StackTraceElement[] trace = (new Exception()).getStackTrace();
        if (trace.length > 1) {
            StackTraceElement traceElement = trace[0];
            String libDetail = String.format("%s##%s##%s##%s", traceElement
                            .getClassName(), traceElement.getMethodName(), traceElement.getFileName(),
                    traceElement.getLineNumber());
            if (!TextUtils.isEmpty(libDetail)) {
                libProperties.put("$lib_detail", libDetail);
            }
        }

        JSONObject eventProperties = new JSONObject();
        eventProperties.put("item_type", itemType);
        eventProperties.put("item_id", itemId);
        eventProperties.put("type", eventType);
        eventProperties.put("time", System.currentTimeMillis());
        eventProperties.put("properties", TimeUtils.formatDate(properties));
        eventProperties.put("lib", libProperties);

        if (!TextUtils.isEmpty(eventProject)) {
            eventProperties.put("project", eventProject);
        }
        mMessages.enqueueEventMessage(eventType, eventProperties);
        SALog.i(TAG, "track event:\n" + JSONUtils.formatJson(eventProperties.toString()));
    } catch (Exception ex) {
        SALog.printStackTrace(ex);
    }
}
 
Example 18
Source File: WindowsRawIpProxyProvider.java    From G-Earth with MIT License 4 votes vote down vote up
private void removeMappingCache() {
    JSONObject connections = getCurrentConnectionsCache();
    connections.remove(INSTANCE_ID.toString());
    saveCurrentConnectionsCache(connections);
}
 
Example 19
Source File: SpecTestCase.java    From firebase-android-sdk with Apache License 2.0 4 votes vote down vote up
private void runSteps(JSONArray steps, JSONObject config) throws Exception {
  try {
    specSetUp(config);
    for (int i = 0; i < steps.length(); ++i) {
      JSONObject step = steps.getJSONObject(i);
      @Nullable JSONArray expectedSnapshotEvents = step.optJSONArray("expectedSnapshotEvents");
      step.remove("expectedSnapshotEvents");
      @Nullable JSONObject expectedState = step.optJSONObject("expectedState");
      step.remove("expectedState");
      int expectedSnapshotsInSyncEvents = step.optInt("expectedSnapshotsInSyncEvents");
      step.remove("expectedSnapshotsInSyncEvents");

      log("    Doing step " + step);
      doStep(step);

      TaskCompletionSource<Void> drainBackgroundQueue = new TaskCompletionSource<>();
      backgroundExecutor.execute(() -> drainBackgroundQueue.setResult(null));
      waitFor(drainBackgroundQueue.getTask());

      if (expectedSnapshotEvents != null) {
        log("      Validating expected snapshot events " + expectedSnapshotEvents);
      }
      validateExpectedSnapshotEvents(expectedSnapshotEvents);
      if (expectedState != null) {
        log("      Validating state expectations " + expectedState);
      }
      validateExpectedState(expectedState);
      validateSnapshotsInSyncEvents(expectedSnapshotsInSyncEvents);
      events.clear();
      acknowledgedDocs.clear();
      rejectedDocs.clear();
    }
  } finally {
    // Ensure that Persistence is torn down even if the test is failing due to a thrown exception
    // so that any open databases are closed. This is important when the LocalStore is backed by
    // SQLite because SQLite opens databases in exclusive mode. If tearDownForSpec were not called
    // after an exception then subsequent attempts to open the SQLite database will fail, making
    // it harder to zero in on the spec tests as a culprit.
    specTearDown();
  }
}
 
Example 20
Source File: AccountContainerTest.java    From ambry with Apache License 2.0 4 votes vote down vote up
/**
 * Tests bad inputs for constructors or methods.
 * @throws Exception Any unexpected exceptions.
 */
@Test
public void badInputs() throws Exception {
  // null account metadata
  TestUtils.assertException(IllegalArgumentException.class, () -> Account.fromJson(null), null);

  // account metadata in wrong format
  JSONObject badMetadata1 = new JSONObject().put("badKey", "badValue");
  TestUtils.assertException(JSONException.class, () -> Account.fromJson(badMetadata1), null);

  // required fields are missing in the metadata
  JSONObject badMetadata2 = deepCopy(refAccountJson);
  badMetadata2.remove(ACCOUNT_ID_KEY);
  TestUtils.assertException(JSONException.class, () -> Account.fromJson(badMetadata2), null);

  // unsupported account json version
  JSONObject badMetadata3 = deepCopy(refAccountJson).put(Account.JSON_VERSION_KEY, 2);
  TestUtils.assertException(IllegalStateException.class, () -> Account.fromJson(badMetadata3), null);

  // invalid account status
  JSONObject badMetadata4 = deepCopy(refAccountJson).put(Account.STATUS_KEY, "invalidAccountStatus");
  TestUtils.assertException(IllegalArgumentException.class, () -> Account.fromJson(badMetadata4), null);

  // null container metadata
  TestUtils.assertException(IllegalArgumentException.class, () -> Container.fromJson(null, refAccountId), null);

  // invalid container status
  JSONObject badMetadata5 = deepCopy(containerJsonList.get(0)).put(Container.STATUS_KEY, "invalidContainerStatus");
  TestUtils.assertException(IllegalArgumentException.class, () -> Container.fromJson(badMetadata5, refAccountId),
      null);

  // required fields are missing.
  JSONObject badMetadata6 = deepCopy(containerJsonList.get(0));
  badMetadata6.remove(CONTAINER_ID_KEY);
  TestUtils.assertException(JSONException.class, () -> Container.fromJson(badMetadata6, refAccountId), null);

  // unsupported container json version
  JSONObject badMetadata7 =
      deepCopy(containerJsonList.get(0)).put(Container.JSON_VERSION_KEY, LATEST_CONTAINER_JSON_VERSION + 1);
  TestUtils.assertException(IllegalStateException.class, () -> Container.fromJson(badMetadata7, refAccountId), null);
}