Java Code Examples for org.json.JSONObject#getJSONObject()
The following examples show how to use
org.json.JSONObject#getJSONObject() .
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: PatchMetaInfo.java From titan-hotfix with Apache License 2.0 | 6 votes |
public static PatchMetaInfo createFromJson(String json) { try { JSONObject jsonObject = new JSONObject(json); PatchMetaInfo patchMetaInfo = new PatchMetaInfo(); patchMetaInfo.targetId = jsonObject.getString(KEY_TARGET_ID); patchMetaInfo.status = jsonObject.getInt(KEY_PATCH_STATUS); patchMetaInfo.loadPolicy = jsonObject.optInt(KEY_LOAD_POLICY, TitanConstant.PATCH_LOAD_POLICY_BOOT); JSONObject versionInfoJson = jsonObject.getJSONObject(KEY_VERSION_INFO); VersionInfo versionInfo = new VersionInfo(); versionInfo.hostVersionName = versionInfoJson.optString(VersionInfo.KEY_HOST_VERSIONNAME); versionInfo.hostVersionCode = versionInfoJson.getInt(VersionInfo.KEY_HOST_VERSIONCODE); versionInfo.patchVersionName = versionInfoJson.optString(VersionInfo.KEY_PATCH_VERSIONNAME); versionInfo.patchVersionCode = versionInfoJson.getInt(VersionInfo.KEY_PATCH_VERSIONCODE); patchMetaInfo.versionInfo = versionInfo; return patchMetaInfo; } catch (Exception e) { // ignore } return null; }
Example 2
Source File: JiraExtractor.java From SnowGraph with Apache License 2.0 | 6 votes |
private Pair<String, Node> createUserNode(JSONObject jsonObj, String key) { if (jsonObj.isNull(key)) { return null; } JSONObject userJsonObj = jsonObj.getJSONObject(key); String name = userJsonObj.optString("name"); String emailAddress = userJsonObj.optString("emailAddress"); String displayName = userJsonObj.optString("displayName"); boolean active = userJsonObj.optBoolean("active"); IssueUserInfo user = new IssueUserInfo(name, EmailAddressDecoder.decode(emailAddress), displayName, active); if (userNodeMap.containsKey(name)) return new ImmutablePair<>(name, userNodeMap.get(name)); Node node = db.createNode(); JiraUtils.createIssueUserNode(user, node); userNodeMap.put(name, node); return new ImmutablePair<>(name, userNodeMap.get(name)); }
Example 3
Source File: TaskTemplate.java From mdw with Apache License 2.0 | 6 votes |
public TaskTemplate(JSONObject json) throws JSONException { this.logicalId = json.getString("logicalId"); this.taskName = json.getString("name"); this.setVersion(AssetVersion.parseVersion(json.getString("version"))); if (json.has("category")) this.taskCategory = json.getString("category"); if (json.has("description")) this.setComment(json.getString("description")); if (json.has("attributes")) { this.attributes = new Attributes(json.getJSONObject("attributes")); setVariablesFromAttribute(TaskAttributeConstant.VARIABLES, null); } String groups = getAttribute(TaskAttributeConstant.GROUPS); if (groups != null) setUserGroupsFromString(groups); }
Example 4
Source File: CrosstabResource.java From Knowage-Server with GNU Affero General Public License v3.0 | 6 votes |
private void addMeasuresScaleFactor(JSONArray fieldOptions, String fieldId, FieldMetadata newFieldMetadata) { if (fieldOptions != null) { for (int i = 0; i < fieldOptions.length(); i++) { try { JSONObject afield = fieldOptions.getJSONObject(i); JSONObject aFieldOptions = afield.getJSONObject(CROSSTAB_ADDITIONAL_DATA_FIELDS_OPTIONS_OPTIONS); String afieldId = afield.getString("id"); String scaleFactor = aFieldOptions.optString(CROSSTAB_ADDITIONAL_DATA_FIELDS_OPTIONS_SCALE_FACTOR); if (afieldId.equals(fieldId) && scaleFactor != null) { newFieldMetadata.setProperty(CROSSTAB_ADDITIONAL_DATA_FIELDS_OPTIONS_SCALE_FACTOR, scaleFactor); return; } } catch (Exception e) { throw new RuntimeException("An unpredicted error occurred while adding measures scale factor", e); } } } }
Example 5
Source File: TencentRelationshipAdaptor.java From YiBo with Apache License 2.0 | 5 votes |
/** * 从JSON对象创建Relationship对象,包级别访问控制 * * @param json * JSON对象 * @return Relationship对象 * @throws LibException */ static Relationship createRelationship(JSONObject json, String identyName) throws LibException { try { Relationship relationship = new Relationship(); JSONObject sourceJson = json.getJSONObject(identyName); relationship.setSourceFollowingTarget(getBoolean("isfans", sourceJson)); relationship.setSourceFollowedByTarget(getBoolean("isidol", sourceJson)); return relationship; } catch (JSONException e) { throw new LibException(LibResultCode.JSON_PARSE_ERROR, e); } }
Example 6
Source File: NpmAuditParser.java From dependency-track with Apache License 2.0 | 5 votes |
/** * Parses the JSON response from the NPM Audit API. * * @param jsonNode the JSON node to parse * @return an AdvisoryResults object * @ */ public List<Advisory> parse(final JsonNode jsonNode) { LOGGER.debug("Parsing JSON node"); final List<Advisory> advisories = new ArrayList<>(); final JSONObject jsonAdvisories = jsonNode.getObject().getJSONObject("advisories"); for (final String key : jsonAdvisories.keySet()) { final Advisory advisory = super.parse(jsonAdvisories.getJSONObject(key)); advisories.add(advisory); } return advisories; }
Example 7
Source File: RestResourceLifeCycleManagementTestCase.java From product-es with Apache License 2.0 | 5 votes |
@Test(groups = {"wso2.greg", "wso2.greg.es"}, description = "PromoteLifeCycle with fault user", dependsOnMethods = {"addLifecycleForRestServiceResources" , "authenticatePublisher", "createRestServiceAssetWithLC"}) public void promoteLifeCycleWithUserWithOutRole() throws JSONException, InterruptedException, IOException { queryParamMap.put("type", "restservice"); queryParamMap.put("lifecycle", "ServiceLifeCycleLC2"); JSONObject LCStateobj = getLifeCycleState(assetId, "restservice"); JSONObject dataObj = LCStateobj.getJSONObject("data"); JSONArray checkItems = dataObj.getJSONArray("checkItems"); //first 2 check list items should be available for non-manager role user Assert.assertEquals(((JSONObject) checkItems.get(0)).getString("isVisible"), "true"); Assert.assertEquals(((JSONObject) checkItems.get(1)).getString("isVisible"), "true"); //checklist item 2 should not be available to non-manager role user Assert.assertEquals(((JSONObject) checkItems.get(2)).getString("isVisible"), "null"); //As check item 2 is not checked promote action is not available JSONObject approvedActionsObj = dataObj.getJSONObject("approvedActions"); Assert.assertEquals(approvedActionsObj.length(), 0); Assert.assertTrue(checkLifeCycleCheckItem(cookieHeader, 0).getStatusCode()==200); checkLifeCycleCheckItem(cookieHeader, 1); ClientResponse responseCheck1 = checkLifeCycleCheckItem(cookieHeader,2); ClientResponse response = genericRestClient.geneticRestRequestPost(publisherUrl + "/assets/" + assetId + "/state", MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON, "nextState=Testing&comment=Completed" , queryParamMap, headerMap, cookieHeader); JSONObject obj = new JSONObject(response.getEntity(String.class)); Assert.assertTrue(response.getStatusCode() == 500, "Fault user accepted"); Assert.assertTrue(obj.get("message").toString().contains("Failed to update asset lifecycle of asset") , "LifeCycle promoted for wrong user"); }
Example 8
Source File: LoginServiceTestHelper.java From wafer-java-server-sdk with MIT License | 5 votes |
public boolean checkBodyHasSession(JSONObject body) { if (!body.has("session")) return false; try { JSONObject session = body.getJSONObject("session"); return session.has("id") && session.has("skey"); } catch (JSONException e) { return false; } }
Example 9
Source File: XMind2MindMapImporter.java From netbeans-mmd-plugin with Apache License 2.0 | 5 votes |
@Nonnull private static String extractTextContentFrom(@Nonnull final JSONObject element, @Nonnull final String tag) { final StringBuilder result = new StringBuilder(); if (element.has(tag)) { final JSONObject object = element.getJSONObject(tag); final String found = object.getString("content"); if (found != null && !found.isEmpty()) { result.append(found.replace("\r", "")); } } return result.toString(); }
Example 10
Source File: Comment.java From android-discourse with Apache License 2.0 | 5 votes |
@Override public void load(JSONObject object) throws JSONException { super.load(object); text = getString(object, "formatted_text"); JSONObject user = object.getJSONObject("creator"); userName = getString(user, "name"); avatarUrl = getString(user, "avatar_url"); createdAt = getDate(object, "created_at"); }
Example 11
Source File: AdapterStubRequest.java From mdw with Apache License 2.0 | 5 votes |
public AdapterStubRequest(JSONObject json) throws JSONException { JSONObject requestJson = json.getJSONObject(getJsonName()); this.masterRequestId = requestJson.getString("masterRequestId"); this.content = requestJson.getString("content"); if (requestJson.has("url")) this.url = requestJson.getString("url"); if (requestJson.has("method")) this.method = requestJson.getString("method"); if (requestJson.has("headers")) this.headers = JsonUtil.getMap(requestJson.getJSONObject("headers")); }
Example 12
Source File: ClientIdentity.java From fabric-chaincode-java with Apache License 2.0 | 5 votes |
/** * parseAttributes returns a map of the attributes associated with an identity. * * @param extensionValue DER-encoded Octet string stored in the attributes * extension of the certificate, as a byte array * @return attrMap {Map<String, String>} a map of identity attributes as key * value pair strings * @throws IOException */ private Map<String, String> parseAttributes(final byte[] extensionValue) throws IOException { final Map<String, String> attrMap = new HashMap<String, String>(); // Create ASN1InputStream from extensionValue try (ByteArrayInputStream inStream = new ByteArrayInputStream(extensionValue); ASN1InputStream asn1InputStream = new ASN1InputStream(inStream)) { // Read the DER object final ASN1Primitive derObject = asn1InputStream.readObject(); if (derObject instanceof DEROctetString) { final DEROctetString derOctetString = (DEROctetString) derObject; // Create attributeString from octets and create JSON object final String attributeString = new String(derOctetString.getOctets(), UTF_8); final JSONObject extJSON = new JSONObject(attributeString); final JSONObject attrs = extJSON.getJSONObject("attrs"); final Iterator<String> keys = attrs.keys(); while (keys.hasNext()) { final String key = keys.next(); // Populate map with attributes and values attrMap.put(key, attrs.getString(key)); } } } catch (final JSONException error) { // creating a JSON object failed // decoded extensionValue is not a string containing JSON logger.error(() -> logger.formatError(error)); // return empty map } return attrMap; }
Example 13
Source File: UnionPayCardBuilderUnitTest.java From braintree_android with MIT License | 5 votes |
@Test public void build_createsUnionPayTokenizeJson() throws JSONException { UnionPayCardBuilder unionPayCardBuilder = new UnionPayCardBuilder() .cvv("123") .enrollmentId("enrollment-id") .expirationYear("expiration-year") .expirationMonth("expiration-month") .cardNumber("card-number") .mobileCountryCode("mobile-country-code") .mobilePhoneNumber("mobile-phone-number") .smsCode("sms-code") .integration("integration") .setSessionId("session-id") .source("source"); JSONObject tokenizePayload = new JSONObject(unionPayCardBuilder.build()); JSONObject creditCard = tokenizePayload.getJSONObject("creditCard"); assertEquals("card-number", creditCard.getString("number")); assertEquals("expiration-month", creditCard.getString("expirationMonth")); assertEquals("expiration-year", creditCard.getString("expirationYear")); assertEquals("123", creditCard.getString("cvv")); JSONObject options = creditCard.getJSONObject("options"); JSONObject unionPayEnrollment = options.getJSONObject("unionPayEnrollment"); assertEquals("enrollment-id", unionPayEnrollment.getString("id")); assertEquals("sms-code", unionPayEnrollment.getString("smsCode")); }
Example 14
Source File: AdminApi.java From android with GNU General Public License v3.0 | 5 votes |
static AdminApi from(JSONObject cjdrouteConf) throws IOException, JSONException { JSONObject admin = cjdrouteConf.getJSONObject("admin"); String[] bind = admin.getString("bind").split(":"); InetAddress address = InetAddress.getByName(bind[0]); int port = Integer.parseInt(bind[1]); byte[] password = admin.getString("password").getBytes(); return new AdminApi(address, port, password); }
Example 15
Source File: AutoFormManualTaskActivity.java From mdw with Apache License 2.0 | 4 votes |
protected void processTaskAction(String messageString) throws ActivityException { try { JSONObject datadoc = new JsonObject(messageString); String compCode = extractFormData(datadoc); // this handles both embedded proc and not datadoc = datadoc.getJSONObject("META"); String action = datadoc.getString(TaskAttributeConstant.TASK_ACTION); CallURL callurl = new CallURL(action); action = callurl.getAction(); if (compCode==null) compCode = datadoc.has(TaskAttributeConstant.URLARG_COMPLETION_CODE) ? datadoc.getString(TaskAttributeConstant.URLARG_COMPLETION_CODE) : null; if (compCode==null) compCode = callurl.getParameter(TaskAttributeConstant.URLARG_COMPLETION_CODE); String subaction = datadoc.has(TaskAttributeConstant.URLARG_ACTION) ? datadoc.getString(TaskAttributeConstant.URLARG_ACTION) : null; if (subaction==null) subaction = callurl.getParameter(TaskAttributeConstant.URLARG_ACTION); if (this.getProcessInstance().isEmbedded() || this.getProcessInstanceOwner().equals("ERROR")) { if (subaction==null) subaction = compCode; if (action.equals("@CANCEL_TASK")) { if (TaskAction.ABORT.equalsIgnoreCase(subaction)) compCode = EventType.EVENTNAME_ABORT + ":process"; else compCode = EventType.EVENTNAME_ABORT; } else { // FormConstants.ACTION_COMPLETE_TASK if (TaskAction.RETRY.equalsIgnoreCase(subaction)) compCode = TaskAction.RETRY; else if (compCode==null) compCode = EventType.EVENTNAME_FINISH; else compCode = EventType.EVENTNAME_FINISH + ":" + compCode; } this.setProcessInstanceCompletionCode(compCode); setReturnCode(null); } else { if (action.equals("@CANCEL_TASK")) { if (TaskAction.ABORT.equalsIgnoreCase(subaction)) compCode = WorkStatus.STATUSNAME_CANCELLED + "::" + EventType.EVENTNAME_ABORT; else compCode = WorkStatus.STATUSNAME_CANCELLED + "::"; setReturnCode(compCode); } else { // FormConstants.ACTION_COMPLETE_TASK setReturnCode(compCode); } } } catch (Exception e) { String errmsg = "Failed to parse task completion message"; logger.error(errmsg, e); throw new ActivityException(-1, errmsg, e); } }
Example 16
Source File: PresenceCallback.java From pubnub-android-chat with MIT License | 4 votes |
@Override public void successCallback(String channel, Object message) { Log.d(Constants.LOGT, "successCallback for presence"); try { ChatterBoxPresenceMessage presenceMessage = new ChatterBoxPresenceMessage(); if (message instanceof JSONObject) { final JSONObject messageJSON = (JSONObject) message; if(!messageJSON.has("action")){ Log.d(Constants.LOGT, "The presence payload has no value because its a status message"); return; } Log.d(Constants.LOGT, messageJSON.toString()); String action = messageJSON.getString("action"); String uuid = messageJSON.getString("uuid"); String timeStamp = messageJSON.getString("timestamp"); Integer occupancyCount = messageJSON.getInt("occupancy"); UserProfile targetProfile = null; presenceMessage.setActionType(action); presenceMessage.setTimeToken(timeStamp); presenceMessage.setOccupancyCount(occupancyCount); presenceMessage.setUuid(uuid); if (action.equals("join")) { targetProfile = new UserProfile(); targetProfile.setId(messageJSON.getString("uuid")); globalPresenceList.put(uuid, targetProfile); //Get the state of the user...don't rely on state //being a part of the join event. if (!messageJSON.has("data")) { pubnub.getState(channel, uuid, this); } } else if ((action.equals("state-change") == true) || (messageJSON.has("data"))) { //assuming you already have a profile for this user targetProfile = globalPresenceList.get(uuid); JSONObject stateData = messageJSON.getJSONObject("data"); String userName = stateData.getString("userName"); String firstName = stateData.getString("firstName"); String lastName = stateData.getString("lastName"); String email = stateData.getString("email"); String imageURL = stateData.getString("imageURL"); String location = stateData.getString("location"); targetProfile.setUserName(userName); targetProfile.setImageURL(imageURL); targetProfile.setLastName(lastName); targetProfile.setFirstName(firstName); targetProfile.setEmail(email); targetProfile.setLocation(location); globalPresenceList.put(uuid, targetProfile); } else if (action.equals("leave") || action.equals("timeout")) { targetProfile = globalPresenceList.remove(uuid); } presenceMessage.setTargetProfile(targetProfile); for (ChatterBoxCallback cb : cblist) { cb.onPresence(presenceMessage); } } } catch (Exception e) { Log.e(Constants.LOGT, "exception while processing presence event", e); } }
Example 17
Source File: DSLParser.java From FATE-Serving with Apache License 2.0 | 4 votes |
public int parseDagFromDSL(String jsonStr) { logger.info("start parse dag from dsl"); try { JSONObject dsl = new JSONObject(jsonStr); JSONObject components = dsl.getJSONObject(Dict.DSL_COMPONENTS); logger.info("start topo sort"); topoSort(components, this.topoRankComponent); logger.info("components size is {}", this.topoRankComponent.size()); for (int i = 0; i < this.topoRankComponent.size(); ++i) { this.componentIds.put(this.topoRankComponent.get(i), i); } for (int i = 0; i < topoRankComponent.size(); ++i) { String componentName = topoRankComponent.get(i); logger.info("component is {}", componentName); JSONObject component = components.getJSONObject(componentName); String[] codePath = ((String) component.get(Dict.DSL_CODE_PATH)).split("/", -1); logger.info("code path splits is {}", codePath); String module = codePath[codePath.length - 1]; logger.info("module is {}", module); componentModuleMap.put(componentName, module); JSONObject upData = component.getJSONObject(Dict.DSL_INPUT).getJSONObject(Dict.DSL_DATA); if (upData != null) { int componentId = this.componentIds.get(componentName); Iterator<String> dataKeyIterator = upData.keys(); while (dataKeyIterator.hasNext()) { String dataKey = dataKeyIterator.next(); JSONArray data = upData.getJSONArray(dataKey); for (int j = 0; j < data.length(); j++) { String upComponent = data.getString(j).split("\\.", -1)[0]; if (!upInputs.containsKey(componentId)) { upInputs.put(componentId, new HashSet<Integer>()); } if (upComponent.equals(Dict.DSL_ARGS)) { upInputs.get(componentId).add(-1); } else { upInputs.get(componentId).add(this.componentIds.get(upComponent)); } } } } } } catch (Exception ex) { ex.printStackTrace(); logger.info("DSLParser init catch error:{}", ex); } logger.info("Finish init DSLParser"); return StatusCode.OK; }
Example 18
Source File: UtilitiesTest.java From unity-ads-android with Apache License 2.0 | 4 votes |
@Test public void testMergeJson() throws Exception { JSONObject objectOne = new JSONObject(); JSONObject objectOneSub = new JSONObject(); JSONObject objectSubOneOne = new JSONObject(); JSONObject objectSubOneOneOne = new JSONObject(); objectSubOneOneOne.put("subsubone", 111); objectSubOneOne.put("subone", 11); objectSubOneOne.put("sub", objectSubOneOneOne); objectOneSub.put("one", 1); objectOneSub.put("sub", objectSubOneOne); objectOneSub.put("override", "primary"); objectOne.put("test", objectOneSub); JSONObject objectTwo = new JSONObject(); JSONObject objectTwoSub = new JSONObject(); JSONObject objectSubTwoTwo = new JSONObject(); JSONObject objectSubTwoTwoTwo = new JSONObject(); objectSubTwoTwoTwo.put("subsubtwo", 222); objectSubTwoTwo.put("subtwo", 22); objectSubTwoTwo.put("sub", objectSubTwoTwoTwo); objectTwoSub.put("two", 2); objectTwoSub.put("sub", objectSubTwoTwo); objectTwoSub.put("override", "secondary"); objectTwo.put("test", objectTwoSub); JSONObject resultObject = Utilities.mergeJsonObjects(objectOne, objectTwo); Log.d("UnityAds", resultObject.toString()); JSONObject testObject = resultObject.getJSONObject("test"); assertEquals("Incorrect 'one' value", 1, testObject.getInt("one")); assertEquals("Incorrect 'two' value", 2, testObject.getInt("two")); JSONObject subObject = testObject.getJSONObject("sub"); assertEquals("Incorrect 'subone' value", 11, subObject.getInt("subone")); assertEquals("Incorrect 'subtwo' value", 22, subObject.getInt("subtwo")); JSONObject subSubObject = subObject.getJSONObject("sub"); assertEquals("Incorrect 'subsubone' value", 111, subSubObject.getInt("subsubone")); assertEquals("Incorrect 'subsubtwo' value", 222, subSubObject.getInt("subsubtwo")); assertEquals("Incorrect 'override' value", "primary", testObject.getString("override")); }
Example 19
Source File: CardBuilderUnitTest.java From braintree_android with MIT License | 4 votes |
@Test public void build_correctlyBuildsACard() throws JSONException { CardBuilder cardBuilder = new CardBuilder() .cardNumber(VISA) .expirationMonth("01") .expirationYear("2015") .cvv("123") .cardholderName("Joe Smith") .firstName("Joe") .lastName("Smith") .company("Company") .streetAddress("1 Main St") .extendedAddress("Unit 1") .locality("Some Town") .postalCode("12345") .region("Some Region") .countryCode("USA") .integration("test-integration") .source("test-source") .validate(true) .setSessionId("test-session-id") .merchantAccountId("merchant-account-id") .authenticationInsightRequested(true); JSONObject json = new JSONObject(cardBuilder.build()); JSONObject jsonCard = json.getJSONObject(CREDIT_CARD_KEY); JSONObject jsonBillingAddress = jsonCard.getJSONObject(BILLING_ADDRESS_KEY); JSONObject jsonMetadata = json.getJSONObject(MetadataBuilder.META_KEY); assertEquals(VISA, jsonCard.getString("number")); assertEquals("01", jsonCard.getString("expirationMonth")); assertEquals("2015", jsonCard.getString("expirationYear")); assertEquals("123", jsonCard.getString("cvv")); assertEquals("Joe Smith", jsonCard.getString("cardholderName")); assertTrue(json.getBoolean("authenticationInsight")); assertEquals("merchant-account-id", json.getString("merchantAccountId")); assertTrue(jsonCard.getJSONObject(PaymentMethodBuilder.OPTIONS_KEY).getBoolean("validate")); assertEquals("Joe", jsonBillingAddress.getString("firstName")); assertEquals("Smith", jsonBillingAddress.getString("lastName")); assertEquals("Company", jsonBillingAddress.getString("company")); assertEquals("1 Main St", jsonBillingAddress.getString("streetAddress")); assertEquals("Unit 1", jsonBillingAddress.getString("extendedAddress")); assertEquals("Some Town", jsonBillingAddress.getString("locality")); assertEquals("12345", jsonBillingAddress.getString("postalCode")); assertEquals("Some Region", jsonBillingAddress.getString("region")); assertEquals("USA", jsonBillingAddress.getString("countryCodeAlpha3")); assertEquals("test-integration", jsonMetadata.getString("integration")); assertEquals("test-source", jsonMetadata.getString("source")); assertEquals("test-session-id", jsonMetadata.getString("sessionId")); }
Example 20
Source File: AbstractJSONAPIResult.java From alfresco-repository with GNU Lesser General Public License v3.0 | 3 votes |
/** * Parses the JSON to set this Java Object values * @param json JSONObject returned by SOLR API * @throws JSONException */ protected void processJson(JSONObject json) throws JSONException { LOGGER.debug("JSON response: {}", json); JSONObject responseHeader = json.getJSONObject("responseHeader"); status = responseHeader.getLong("status"); queryTime = responseHeader.getLong("QTime"); processCoresInfoJson(json); }