Java Code Examples for com.eclipsesource.json.JsonObject#toString()
The following examples show how to use
com.eclipsesource.json.JsonObject#toString() .
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: Config.java From JWT4B with GNU General Public License v3.0 | 6 votes |
private static String generateDefaultConfigFile() { JsonObject configJO = new JsonObject(); JsonArray jwtKeywordsJA = new JsonArray(); for (String jwtKeyword : jwtKeywords) { jwtKeywordsJA.add(jwtKeyword); } JsonArray tokenKeywordsJA = new JsonArray(); for (String tokenKeyword : tokenKeywords) { tokenKeywordsJA.add(tokenKeyword); } configJO.add("resetEditor", true); configJO.add("highlightColor", highlightColor); configJO.add("interceptComment", interceptComment); configJO.add("jwtKeywords",jwtKeywordsJA); configJO.add("tokenKeywords",tokenKeywordsJA); configJO.add("cveAttackModePublicKey", cveAttackModePublicKey); configJO.add("cveAttackModePrivateKey", cveAttackModePrivateKey); return configJO.toString(WriterConfig.PRETTY_PRINT); }
Example 2
Source File: BoxFileUploadSession.java From box-java-sdk with Apache License 2.0 | 6 votes |
private String getCommitBody(List<BoxFileUploadSessionPart> parts, Map<String, String> attributes) { JsonObject jsonObject = new JsonObject(); JsonArray array = new JsonArray(); for (BoxFileUploadSessionPart part: parts) { JsonObject partObj = new JsonObject(); partObj.add("part_id", part.getPartId()); partObj.add("offset", part.getOffset()); partObj.add("size", part.getSize()); array.add(partObj); } jsonObject.add("parts", array); if (attributes != null) { JsonObject attrObj = new JsonObject(); for (String key: attributes.keySet()) { attrObj.add(key, attributes.get(key)); } jsonObject.add("attributes", attrObj); } return jsonObject.toString(); }
Example 3
Source File: ControlTowerIrDatabase.java From IrScrutinizer with GNU General Public License v3.0 | 5 votes |
public void login() throws MalformedURLException, IOException, LoginException { JsonObject jsonObject = new JsonObject(); jsonObject.add("Email", email); jsonObject.add("Password", password); String payload = jsonObject.toString(); JsonObject response = postAndGetObject("/account/login", payload); String status = response.get("Status").asString(); if (!status.equals("success")) throw new LoginException(response.get("Message").asString()); JsonObject acct = response.get("Account").asObject(); evaluateAccount(acct); }
Example 4
Source File: SimpleStatisticsReporter.java From plog with Apache License 2.0 | 5 votes |
public final String toJSON() { final JsonObject result = new JsonObject() .add("version", getPlogVersion()) .add("uptime", System.currentTimeMillis() - startTime) .add("udp_simple_messages", udpSimpleMessages.get()) .add("udp_invalid_version", udpInvalidVersion.get()) .add("v0_invalid_type", v0InvalidType.get()) .add("v0_invalid_multipart_header", v0InvalidMultipartHeader.get()) .add("unknown_command", unknownCommand.get()) .add("v0_commands", v0Commands.get()) .add("exceptions", exceptions.get()) .add("unhandled_objects", unhandledObjects.get()) .add("holes_from_dead_port", holesFromDeadPort.get()) .add("holes_from_new_message", holesFromNewMessage.get()) .add("v0_fragments", arrayForLogStats(v0MultipartMessageFragments)) .add("v0_invalid_checksum", arrayForLogStats(v0InvalidChecksum)) .add("v0_invalid_fragments", arrayForLogLogStats(invalidFragments)) .add("dropped_fragments", arrayForLogLogStats(droppedFragments)); if (defragmenter != null) { final CacheStats cacheStats = defragmenter.getCacheStats(); result.add("defragmenter", new JsonObject() .add("evictions", cacheStats.evictionCount()) .add("hits", cacheStats.hitCount()) .add("misses", cacheStats.missCount())); } final JsonArray handlersStats = new JsonArray(); result.add("handlers", handlersStats); for (Handler handler : handlers) { final JsonObject statsCandidate = handler.getStats(); final JsonObject stats = (statsCandidate == null) ? new JsonObject() : statsCandidate; handlersStats.add(stats.set("name", handler.getName())); } return result.toString(); }
Example 5
Source File: JSONRequestInterceptor.java From box-java-sdk with Apache License 2.0 | 5 votes |
public static RequestInterceptor respondWith(final JsonObject json) { return new RequestInterceptor() { @Override public BoxAPIResponse onRequest(BoxAPIRequest request) { return new BoxJSONResponse() { @Override public String getJSON() { return json.toString(); } }; } }; }
Example 6
Source File: BoxJSONObject.java From box-java-sdk with Apache License 2.0 | 5 votes |
/** * Gets a JSON string containing any pending changes to this object that can be sent back to the Box API. * @return a JSON string containing the pending changes. */ public String getPendingChanges() { JsonObject jsonObject = this.getPendingJSONObject(); if (jsonObject == null) { return null; } return jsonObject.toString(); }
Example 7
Source File: BoxAPIConnection.java From box-java-sdk with Apache License 2.0 | 5 votes |
/** * Saves the state of this connection to a string so that it can be persisted and restored at a later time. * * <p>Note that proxy settings aren't automatically saved or restored. This is mainly due to security concerns * around persisting proxy authentication details to the state string. If your connection uses a proxy, you will * have to manually configure it again after restoring the connection.</p> * * @see #restore * @return the state of this connection. */ public String save() { JsonObject state = new JsonObject() .add("accessToken", this.accessToken) .add("refreshToken", this.refreshToken) .add("lastRefresh", this.lastRefresh) .add("expires", this.expires) .add("userAgent", this.userAgent) .add("tokenURL", this.tokenURL) .add("baseURL", this.baseURL) .add("baseUploadURL", this.baseUploadURL) .add("autoRefresh", this.autoRefresh) .add("maxRetryAttempts", this.maxRetryAttempts); return state.toString(); }
Example 8
Source File: ControlTowerIrDatabase.java From IrScrutinizer with GNU General Public License v3.0 | 5 votes |
public String getStatus() throws IOException { if (apiKey == null) return "Not logged in"; JsonObject obj = getJsonObject("account" + apiKeyString('?')); evaluateAccount(obj); return obj.toString(); }
Example 9
Source File: AndroidInjections.java From CrossMobile with GNU Lesser General Public License v3.0 | 5 votes |
@Override public String toString() { if (isEmpty()) return ""; JsonObject root = new JsonObject(); if (!appSection.isEmpty()) root.add("appSection", toArray(appSection)); if (!gradleExt.isEmpty()) root.add("gradleExt", toArray(gradleExt)); if (!gradleBuildDep.isEmpty()) root.add("gradleBuildDep", toArray(gradleBuildDep)); return root.toString(); }
Example 10
Source File: ReflectionHelper.java From cineast with MIT License | 5 votes |
/** * Instantiates an object from a provided JSON with the following structure: * { * "name" : the name of the class, (optional) * "class" : the class name including package name of the class, (optional) * "config" : JSON object containing configuration which is passed as is to the constructor (optional) * } * * Either 'name' or 'class' needs to be set, 'name' has priority over 'class'. * * @param json * @param expectedSuperClass * @param expectedPackage * @throws IllegalArgumentException in case neither 'name' nor 'class' is specified * @throws InstantiationException in case instantiation fails or the requested class does not match the expected super class * @throws ClassNotFoundException in case the class to instantiate was not found */ public static <T> T instanciateFromJson(JsonObject json, Class<T> expectedSuperClass, String expectedPackage) throws IllegalArgumentException, InstantiationException, ClassNotFoundException{ Class<T> targetClass = getClassFromJson(json, expectedSuperClass, expectedPackage); if(targetClass == null){ throw new ClassNotFoundException("No class found matching specification in " + json.toString()); } T instance = null; if(json.get("config") == null){ instance = instanciate(targetClass); }else{ try{ instance = instanciate(targetClass, json.get("config").asObject()); }catch(UnsupportedOperationException notAnObject){ LOGGER.warn("'config' was not an object during class instanciation in instanciateFromJson"); } } if(instance == null){ throw new InstantiationException(); } return instance; }
Example 11
Source File: ValidationResult.java From r2cloud with Apache License 2.0 | 5 votes |
public String toJson() { JsonObject result = Json.object(); if (!isEmpty()) { JsonObject errors = Json.object(); if (general != null) { errors.add("general", general); } for (Entry<String, String> cur : entrySet()) { errors.add(cur.getKey(), cur.getValue()); } result.add("errors", errors); } return result.toString(); }
Example 12
Source File: ZCashClientCaller.java From zencash-swing-wallet-ui with MIT License | 5 votes |
public synchronized String getRawTransaction(String txID) throws WalletCallException, IOException, InterruptedException { JsonObject jsonTransaction = this.executeCommandAndGetJsonObject( "gettransaction", wrapStringParameter(txID)); return jsonTransaction.toString(WriterConfig.PRETTY_PRINT); }
Example 13
Source File: MessagingPanel.java From zencash-swing-wallet-ui with MIT License | 5 votes |
public void sendIdentityMessageTo(MessagingIdentity contactIdentity) throws InterruptedException, IOException, WalletCallException { // Only a limited set of values is sent over the wire, due to the limit of 330 // characters. // TODO: use protocol versions with larger messages MessagingIdentity ownIdentity = this.messagingStorage.getOwnIdentity(); JsonObject innerIDObject = new JsonObject(); innerIDObject.set("nickname", ownIdentity.getNickname()); innerIDObject.set("firstname", ownIdentity.getFirstname()); innerIDObject.set("surname", ownIdentity.getSurname()); innerIDObject.set("senderidaddress", ownIdentity.getSenderidaddress()); innerIDObject.set("sendreceiveaddress", ownIdentity.getSendreceiveaddress()); JsonObject outerObject = new JsonObject(); outerObject.set("zenmessagingidentity", innerIDObject); String identityString = outerObject.toString(); // Check and send the messaging identity as a message if (identityString.length() <= 330) // Protocol V1 restriction { this.sendMessage(identityString, contactIdentity); } else { JOptionPane.showMessageDialog( this.parentFrame, "The size of your messaging identity is unfortunately too large to be sent\n" + "as a message. Your contact will have to import your messaging identity\n" + "manually from a json file...", "Messaging identity size is too large!", JOptionPane.ERROR_MESSAGE); return; } }
Example 14
Source File: DeleteProgram.java From REST-Sample-Code with MIT License | 4 votes |
public String bodyBuilder(){ JsonObject body = new JsonObject(); return body.toString(); }
Example 15
Source File: BoxJSONRequest.java From box-java-sdk with Apache License 2.0 | 4 votes |
/** * Sets the body of this request to a given JsonObject. * @param body the JsonObject to use as the body. */ public void setBody(JsonObject body) { super.setBody(body.toString()); this.jsonValue = body; }
Example 16
Source File: WeatherService.java From whirlpool with Apache License 2.0 | 4 votes |
@Override protected void collectData(Gson gson, String user, List<String> subscriptions) { Map<String, String> subscriptionData = new HashMap<>(); for (String cityState : subscriptions) { try (CloseableHttpClient httpClient = HttpClientHelper.buildHttpClient()) { String url = WEATHER_URL_START; url += URLEncoder.encode(cityState, "UTF-8"); url += WEATHER_URL_END; HttpUriRequest query = RequestBuilder.get() .setUri(url) .build(); try (CloseableHttpResponse queryResponse = httpClient.execute(query)) { HttpEntity entity = queryResponse.getEntity(); if (entity != null) { String data = EntityUtils.toString(entity); JsonObject jsonObject = JsonObject.readFrom(data); if (jsonObject != null) { JsonValue jsonValue = jsonObject.get("query"); if (!jsonValue.isNull()) { jsonObject = jsonValue.asObject(); jsonValue = jsonObject.get("results"); if (!jsonValue.isNull()) { jsonObject = jsonValue.asObject(); jsonObject = jsonObject.get("channel").asObject(); jsonObject = jsonObject.get("item").asObject(); jsonObject = jsonObject.get("condition").asObject(); String weatherData = jsonObject.toString(); weatherData = weatherData.replaceAll("\\\\\"", "\""); subscriptionData.put(cityState, weatherData); } else { subscriptionData.put(cityState, "{\"result\":\"notfound\"}"); } } } else { subscriptionData.put(cityState, "{\"result\":\"notfound\"}"); } } } } catch (Throwable throwable) { logger.error(throwable.getMessage(), throwable); } } DataResponse response = new DataResponse(); response.setType("WeatherResponse"); response.setId(user); response.setResult(MessageConstants.SUCCESS); response.setSubscriptionData(subscriptionData); responseQueue.add(gson.toJson(response)); }
Example 17
Source File: MessagingPanel.java From zencash-swing-wallet-ui with MIT License | 4 votes |
public void addMessagingGroup() { try { CreateGroupDialog cgd = new CreateGroupDialog( this, this.parentFrame, this.messagingStorage, this.errorReporter, this.clientCaller, this.labelStorage); cgd.setVisible(true); if (!cgd.isOKPressed()) { return; } // So a group is created - we need to ask the user if he wishes to send an identity message MessagingIdentity createdGroup = cgd.getCreatedGroup(); int sendIDChoice = JOptionPane.showConfirmDialog( this.parentFrame, "Do you wish to send a limited sub-set of your contact details to group\n" + createdGroup.getDiplayString() + "\n" + "This will allow other group members to know your messaging identity.", "Send contact details?", JOptionPane.YES_NO_OPTION); // TODO: code duplication with import if (sendIDChoice == JOptionPane.YES_OPTION) { // Only a limited set of values is sent over the wire, due to the limit of 330 // characters. // TODO: use protocol versions with larger messages MessagingIdentity ownIdentity = this.messagingStorage.getOwnIdentity(); JsonObject innerIDObject = new JsonObject(); innerIDObject.set("nickname", ownIdentity.getNickname()); innerIDObject.set("firstname", ownIdentity.getFirstname()); innerIDObject.set("surname", ownIdentity.getSurname()); innerIDObject.set("senderidaddress", ownIdentity.getSenderidaddress()); innerIDObject.set("sendreceiveaddress", ownIdentity.getSendreceiveaddress()); JsonObject outerObject = new JsonObject(); outerObject.set("zenmessagingidentity", innerIDObject); String identityString = outerObject.toString(); // Check and send the messaging identity as a message if (identityString.length() <= 330) // Protocol V1 restriction { this.sendMessage(identityString, createdGroup); } else { JOptionPane.showMessageDialog( this.parentFrame, "The size of your messaging identity is unfortunately too large to be sent\n" + "as a message.", "Messaging identity size is too large!", JOptionPane.ERROR_MESSAGE); return; } } } catch (Exception ex) { this.errorReporter.reportError(ex, false); } }
Example 18
Source File: BoxWebLink.java From box-java-sdk with Apache License 2.0 | 2 votes |
/** * Constructs an Info object using an already parsed JSON object. * @param jsonObject the parsed JSON object. */ public Info(JsonObject jsonObject) { super(jsonObject.toString()); }