Java Code Examples for com.google.gson.JsonObject#add()
The following examples show how to use
com.google.gson.JsonObject#add() .
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: SparqlDataSourceTest.java From Server.Java with MIT License | 6 votes |
/** * * @throws Exception */ @BeforeClass public static void setUpClass() throws Exception { final String typeName = "SparqlSourceType"; if ( ! DataSourceTypesRegistry.isRegistered(typeName) ) { DataSourceTypesRegistry.register( typeName, new SparqlDataSourceType() ); } String tmpdir = System.getProperty("java.io.tmpdir"); jena = new File(tmpdir, "ldf-sparql-test"); jena.mkdir(); dataset = TDBFactory.createDataset(jena.getAbsolutePath()); Model model = dataset.getDefaultModel(); InputStream in = ClassLoader.getSystemResourceAsStream("demo.nt"); RDFDataMgr.read(model, in, Lang.NTRIPLES); // Dynamically-generated port comes from pom.xml configuration: build-helper-maven-plugin int fusekiPort = Integer.parseInt(System.getProperty("fuseki.port")); // Create Fuseki, loaded with the test dataset fuseki = FusekiServer.create().setPort(fusekiPort).add("/ds", dataset).build(); fuseki.start(); // Everything is in place, now create the LDF datasource JsonObject config = createConfig("sparql test", "sparql test", typeName); JsonObject settings = new JsonObject(); settings.addProperty("endpoint", "http://localhost:" + fusekiPort + "/ds"); config.add("settings", settings); setDatasource(DataSourceFactory.create(config)); }
Example 2
Source File: DockerAccessWithHcClient.java From docker-maven-plugin with Apache License 2.0 | 6 votes |
@Override public String createExecContainer(String containerId, Arguments arguments) throws DockerAccessException { String url = urlBuilder.createExecContainer(containerId); JsonObject request = new JsonObject(); request.addProperty("Tty", true); request.addProperty("AttachStdin", false); request.addProperty("AttachStdout", true); request.addProperty("AttachStderr", true); request.add("Cmd", JsonFactory.newJsonArray(arguments.getExec())); String execJsonRequest = request.toString(); log.verbose(Logger.LogVerboseCategory.API,"POST to %s with %s", url, execJsonRequest); try { String response = delegate.post(url, execJsonRequest, new ApacheHttpClientDelegate.BodyResponseHandler(), HTTP_CREATED); JsonObject json = JsonFactory.newJsonObject(response); if (json.has("Warnings")) { logWarnings(json); } return json.get("Id").getAsString(); } catch (IOException e) { throw new DockerAccessException(e, "Unable to exec [%s] on container [%s]", request.toString(), containerId); } }
Example 3
Source File: JsonHandler.java From wings with Apache License 2.0 | 6 votes |
public JsonElement serialize(Binding binding, Type typeOfSrc, JsonSerializationContext context) { if(binding.isSet()) { JsonArray arr = new JsonArray(); for(WingsSet s : binding) arr.add(context.serialize((Binding)s, typeOfSrc)); return arr; } else { JsonObject obj = new JsonObject(); if (binding.isURIBinding()) { obj.add("id", new JsonPrimitive(binding.getID())); obj.add("type", new JsonPrimitive("uri")); } else if(binding.getValue() != null) { ValueBinding vb = (ValueBinding) binding; String datatype = vb.getDatatype(); if(datatype== null) datatype = KBUtils.XSD + "string"; obj.add("value", new JsonPrimitive(vb.getValueAsString())); obj.add("datatype", new JsonPrimitive(datatype)); obj.add("type", new JsonPrimitive("literal")); } return obj; } }
Example 4
Source File: Metrics.java From PlayerVaults with GNU General Public License v3.0 | 6 votes |
private JsonObject getRequestJsonObject() { JsonObject chart = new JsonObject(); chart.addProperty("chartId", chartId); try { JsonObject data = getChartData(); if (data == null) { // If the data is null we don't send the chart. return null; } chart.add("data", data); } catch (Throwable t) { if (logFailedRequests) { Bukkit.getLogger().log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t); } return null; } return chart; }
Example 5
Source File: Room.java From kurento-java with Apache License 2.0 | 6 votes |
public void sendParticipantNames(RoomParticipant user) { checkClosed(); log.debug("PARTICIPANT {}: sending a list of participants", user.getName()); final JsonArray participantsArray = new JsonArray(); for (final RoomParticipant participant : this.getParticipants()) { log.debug("PARTICIPANT {}: visiting participant", user.getName(), participant.getName()); if (!participant.equals(user)) { final JsonElement participantName = new JsonPrimitive(participant.getName()); participantsArray.add(participantName); } } final JsonObject existingParticipantsMsg = new JsonObject(); existingParticipantsMsg.addProperty("id", "existingParticipants"); existingParticipantsMsg.add("data", participantsArray); log.debug("PARTICIPANT {}: sending a list of {} participants", user.getName(), participantsArray.size()); user.sendMessage(existingParticipantsMsg); }
Example 6
Source File: QueryBuilders.java From flummi with Apache License 2.0 | 5 votes |
public static JsonObject existsFilter(String fieldName) { JsonObject jsonObject = new JsonObject(); JsonObject existsObject = new JsonObject(); jsonObject.add("exists", existsObject); existsObject.add("field", new JsonPrimitive(fieldName)); return jsonObject; }
Example 7
Source File: MultiANewArrayInsnNodeSerializer.java From maple-ir with GNU General Public License v3.0 | 5 votes |
@Override public JsonElement serialize(MultiANewArrayInsnNode src, Type typeOfSrc, JsonSerializationContext context) { JsonObject object = new JsonObject(); object.add("desc", context.serialize(src.desc)); object.add("dims", context.serialize(src.dims)); return object; }
Example 8
Source File: UrlBuilder.java From jkube with Eclipse Public License 2.0 | 5 votes |
private void addFilters(Builder builder, String... filter) { if (filter.length > 0) { if (filter.length % 2 != 0) { throw new IllegalArgumentException("Filters must be given as key value pairs and not " + Arrays.asList(filter)); } JsonObject filters = new JsonObject(); for (int i = 0; i < filter.length; i +=2) { JsonArray value = new JsonArray(); value.add(filter[i+1]); filters.add(filter[i],value); } builder.p("filters",filters.toString()); } }
Example 9
Source File: RdapTestHelper.java From nomulus with Apache License 2.0 | 5 votes |
static void addNonDomainBoilerplateNotices(JsonObject jsonObject, String linkBase) { if (!jsonObject.has("notices")) { jsonObject.add("notices", new JsonArray()); } JsonArray notices = jsonObject.getAsJsonArray("notices"); notices.add(createTosNotice(linkBase)); notices.add( GSON.toJsonTree( ImmutableMap.of( "description", ImmutableList.of( "This response conforms to the RDAP Operational Profile for gTLD" + " Registries and Registrars version 1.0")))); }
Example 10
Source File: WxMpShakeAroundDeviceBindPageQuery.java From weixin-java-tools with Apache License 2.0 | 5 votes |
public String toJsonString(){ JsonObject jsonObject = new JsonObject(); jsonObject.add("device_identifier", deviceIdentifier.toJsonObject()); JsonArray jsonArray = new JsonArray(); for(Integer pageid: pageIds){ jsonArray.add(pageid); } jsonObject.add("page_ids", jsonArray); return jsonObject.toString(); }
Example 11
Source File: VmService.java From flutter-intellij with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * The [evaluateInFrame] RPC is used to evaluate an expression in the context of a particular * stack frame. [frameIndex] is the index of the desired Frame, with an index of [0] indicating * the top (most recent) frame. * @param scope This parameter is optional and may be null. * @param disableBreakpoints This parameter is optional and may be null. */ public void evaluateInFrame(String isolateId, int frameIndex, String expression, Map<String, String> scope, Boolean disableBreakpoints, EvaluateInFrameConsumer consumer) { final JsonObject params = new JsonObject(); params.addProperty("isolateId", isolateId); params.addProperty("frameIndex", frameIndex); params.addProperty("expression", expression); if (scope != null) params.add("scope", convertMapToJsonObject(scope)); if (disableBreakpoints != null) params.addProperty("disableBreakpoints", disableBreakpoints); request("evaluateInFrame", params, consumer); }
Example 12
Source File: JsonSchema.java From incubator-gobblin with Apache License 2.0 | 5 votes |
/** * Build a {@link JsonSchema} using {@link JsonArray} * This will create a {@link SchemaType} of {@link SchemaType#ROOT} * @param jsonArray */ public JsonSchema(JsonArray jsonArray) { JsonObject jsonObject = new JsonObject(); JsonObject dataType = new JsonObject(); jsonObject.addProperty(COLUMN_NAME_KEY, DEFAULT_RECORD_COLUMN_NAME); dataType.addProperty(TYPE_KEY, RECORD.toString()); dataType.add(RECORD_FIELDS_KEY, jsonArray); jsonObject.add(DATA_TYPE_KEY, dataType); setJsonSchemaProperties(jsonObject); this.type = RECORD; this.json = jsonObject; this.jsonArray = jsonArray; this.schemaNestedLevel = ROOT; }
Example 13
Source File: KcaPoiDBAPI.java From kcanotify with GNU General Public License v3.0 | 5 votes |
public static void sendEquipDevData(String items, int secretary, int itemId, int teitokuLv, boolean successful) { if (teitokuLv < 1 || secretary < 0 || itemId < 0) return; JsonObject response = new JsonObject(); response.add("items", gson.fromJson(items, JsonArray.class)); response.addProperty("secretary", secretary); response.addProperty("itemId", itemId); response.addProperty("teitokuLv", teitokuLv); response.addProperty("successful", successful); response.addProperty("origin", USER_AGENT); new poiDbRequest().execute(REQ_EQUIP_DEV, KcaUtils.format("data=%s", response.toString())); }
Example 14
Source File: NodeMessage.java From java-trader with Apache License 2.0 | 5 votes |
public String toString() { JsonObject json = new JsonObject(); json.addProperty(FIELD_TYPE, type.name()); json.addProperty(FIELD_ID, id); json.addProperty(FIELD_CORRID, corrId); json.addProperty(FIELD_ERROR_CODE, errCode); if ( errCode!=0 ) { json.addProperty(FIELD_ERROR_MSG, errMsg); } for(String key:fields.keySet()) { json.add(key, JsonUtil.object2json(fields.get(key))); } return json.toString(); }
Example 15
Source File: CiphertextUtils.java From cerberus with Apache License 2.0 | 5 votes |
/** Convert a ParsedCiphertext in the 'AWS Encryption SDK Message Format' to a JsonObject. */ public static JsonObject toJsonObject(ParsedCiphertext parsedCiphertext) { JsonObject o = new JsonObject(); o.addProperty("version", parsedCiphertext.getVersion()); o.addProperty("type", parsedCiphertext.getType().toString()); o.addProperty("cryptoAlgoId", parsedCiphertext.getCryptoAlgoId().toString()); o.addProperty("messageId", Base64.getEncoder().encodeToString(parsedCiphertext.getMessageId())); o.add("encryptionContext", new Gson().toJsonTree(parsedCiphertext.getEncryptionContextMap())); o.addProperty("keyBlobCount", parsedCiphertext.getEncryptedKeyBlobCount()); JsonArray keyBlobs = new JsonArray(); for (KeyBlob keyBlob : parsedCiphertext.getEncryptedKeyBlobs()) { JsonObject blob = new JsonObject(); blob.addProperty("providerId", keyBlob.getProviderId()); try { blob.addProperty("providerInfo", new String(keyBlob.getProviderInformation(), "UTF-8")); } catch (UnsupportedEncodingException e) { LoggerFactory.getLogger("com.nike.cerberus.util.CiphertextUtils") .error("Failed to create new string from key blob provider information", e); throw new ApiException(DefaultApiError.INTERNAL_SERVER_ERROR); } blob.addProperty("isComplete:", keyBlob.isComplete()); keyBlobs.add(blob); } o.add("keyBlobs", keyBlobs); o.addProperty("contentType", parsedCiphertext.getContentType().toString()); return o; }
Example 16
Source File: Metrics.java From UltimateChat with GNU General Public License v3.0 | 5 votes |
@Override public JsonObject getChartData() throws Exception { JsonObject data = new JsonObject(); JsonObject values = new JsonObject(); Map<String, Map<String, Integer>> map = callable.call(); if (map == null || map.isEmpty()) { // Null = skip the chart return null; } boolean reallyAllSkipped = true; for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) { JsonObject value = new JsonObject(); boolean allSkipped = true; for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) { value.addProperty(valueEntry.getKey(), valueEntry.getValue()); allSkipped = false; } if (!allSkipped) { reallyAllSkipped = false; values.add(entryValues.getKey(), value); } } if (reallyAllSkipped) { // Null = skip the chart return null; } data.add("values", values); return data; }
Example 17
Source File: Kitsu.java From houdoku with MIT License | 4 votes |
@Override public void update(String id, Track track, boolean safe, boolean can_add) throws IOException, NotAuthenticatedException { if (!this.authenticated) { throw new NotAuthenticatedException(); } Track track_old = getSeriesInList(id); if (track_old == null) { if (!can_add) { // series isn't in the user's list and we aren't allowed to add it, so do nothing return; } // The series doesn't exist in the list, so add it. That method doesn't set any // properties (i.e. progress or status), so we'll continue with this method to do an // update request as well track_old = add(id); } Status status = track.getStatus() == null ? track_old.getStatus() : track.getStatus(); int progress = track.getProgress() == null ? track_old.getProgress() : track.getProgress(); int score = track.getScore() == null ? track_old.getScore() : track.getScore(); // in safe mode, only update progress if current progress is greater than the desired if (safe) { Integer progress_old = track_old.getProgress(); Integer progress_new = track.getProgress(); if (progress_old != null && progress_new != null) { if (progress_old > progress_new) { progress = progress_old; } } } Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/vnd.api+json"); JsonObject json_attributes = new JsonObject(); json_attributes.addProperty("status", statuses.get(status)); json_attributes.addProperty("progress", progress); json_attributes.addProperty("ratingTwenty", score / 5); JsonObject json_content = new JsonObject(); json_content.addProperty("type", "libraryEntries"); json_content.addProperty("id", track_old.getListId()); json_content.add("attributes", json_attributes); JsonObject json = new JsonObject(); json.add("data", json_content); PATCH(client, PROTOCOL + "://" + DOMAIN + "/api/edge/library-entries/" + track_old.getListId(), json.toString(), headers, MediaType.parse("application/vnd.api+json; charset=utf-8")); }
Example 18
Source File: SellConfirmCoinifyActivity.java From guarda-android-wallets with GNU General Public License v3.0 | 4 votes |
private void coinifyTrade() { //transferIn JsonObject transferIn = new JsonObject(); transferIn.addProperty("medium", "blockchain"); //transferOut JsonObject transferOut = new JsonObject(); transferOut.addProperty("medium", "bank"); transferOut.addProperty("mediumReceiveAccountId", getIntent().getIntExtra(Extras.COINIFY_BANK_ACC_ID, 0)); JsonObject trade = new JsonObject(); trade.addProperty("priceQuoteId", getIntent().getIntExtra(Extras.COINIFY_QUOTE_ID, 0)); trade.add("transferIn", transferIn); trade.add("transferOut", transferOut); Log.d("psd", "PurchaseCoins coinifyTrade - json trade = " + trade.toString()); Requestor.coinifyTradeSell(sharedManager.getCoinifyAccessToken(), trade, new ApiMethods.RequestListener() { @Override public void onSuccess(Object response) { if (response != null) { CoinifyTradeRespSell ctr = (CoinifyTradeRespSell) response; sharedManager.setCoinifyLastTradeId(ctr.getId()); sharedManager.setCoinifyLastTradeState(ctr.getState()); sharedManager.setCoinifyLastTradeUptime(ctr.getUpdateTime()); changeNowGenAddr(ctr.getTransferIn().getDetails().getAccount()); Log.d("psd", "PurchaseCoins coinifyTrade success - trade id = " + ctr.getId()); } } @Override public void onFailure(String msg) { closeProgress(); JsonParser jp = new JsonParser(); JsonObject jo = jp.parse(msg).getAsJsonObject(); Toast.makeText(getApplicationContext(), jo.get("error_description").toString(), Toast.LENGTH_LONG).show(); Log.d("psd", "PurchaseCoins coinifyTrade onFailure - " + msg); } }); }
Example 19
Source File: MCREchoResource.java From mycore with GNU General Public License v3.0 | 4 votes |
@GET @Produces(MediaType.APPLICATION_JSON) @MCRRestrictedAccess(MCRRequireLogin.class) public String doEcho() { Gson gson = new Gson(); JsonObject jRequest = new JsonObject(); jRequest.addProperty("secure", request.isSecure()); jRequest.addProperty("authType", request.getAuthType()); jRequest.addProperty("context", request.getContextPath()); jRequest.addProperty("localAddr", request.getLocalAddr()); jRequest.addProperty("localName", request.getLocalName()); jRequest.addProperty("method", request.getMethod()); jRequest.addProperty("pathInfo", request.getPathInfo()); jRequest.addProperty("protocol", request.getProtocol()); jRequest.addProperty("queryString", request.getQueryString()); jRequest.addProperty("remoteAddr", request.getRemoteAddr()); jRequest.addProperty("remoteHost", request.getRemoteHost()); jRequest.addProperty("remoteUser", request.getRemoteUser()); jRequest.addProperty("remotePort", request.getRemotePort()); jRequest.addProperty("requestURI", request.getRequestURI()); jRequest.addProperty("scheme", request.getScheme()); jRequest.addProperty("serverName", request.getServerName()); jRequest.addProperty("servletPath", request.getServletPath()); jRequest.addProperty("serverPort", request.getServerPort()); HttpSession session = request.getSession(false); List<String> attributes = Collections.list(session.getAttributeNames()); JsonObject sessionJSON = new JsonObject(); JsonObject attributesJSON = new JsonObject(); attributes.forEach(attr -> attributesJSON.addProperty(attr, session.getAttribute(attr).toString())); sessionJSON.add("attributes", attributesJSON); sessionJSON.addProperty("id", session.getId()); sessionJSON.addProperty("creationTime", session.getCreationTime()); sessionJSON.addProperty("lastAccessedTime", session.getLastAccessedTime()); sessionJSON.addProperty("maxInactiveInterval", session.getMaxInactiveInterval()); sessionJSON.addProperty("isNew", session.isNew()); jRequest.add("session", sessionJSON); jRequest.addProperty("localPort", request.getLocalPort()); JsonArray jLocales = new JsonArray(); Enumeration<Locale> locales = request.getLocales(); while (locales.hasMoreElements()) { jLocales.add(gson.toJsonTree(locales.nextElement().toString())); } jRequest.add("locales", jLocales); JsonObject header = new JsonObject(); jRequest.add("header", header); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); String headerValue = request.getHeader(headerName); header.addProperty(headerName, headerValue); } JsonObject parameter = new JsonObject(); jRequest.add("parameter", parameter); for (Map.Entry<String, String[]> param : request.getParameterMap().entrySet()) { if (param.getValue().length == 1) { parameter.add(param.getKey(), gson.toJsonTree(param.getValue()[0])); } else { parameter.add(param.getKey(), gson.toJsonTree(param.getValue())); } } return jRequest.toString(); }
Example 20
Source File: JsonUtil.java From camunda-bpm-platform with Apache License 2.0 | 4 votes |
public static <T> void addField(JsonObject jsonObject, String name, JsonObjectConverter<T> converter, T value) { if (jsonObject != null && name != null && converter != null && value != null) { jsonObject.add(name, converter.toJsonObject(value)); } }