Java Code Examples for com.google.gson.JsonObject.add()

The following are Jave code examples for showing how to use add() of the com.google.gson.JsonObject class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: filestack-java   File: Client.java   View Source Code Vote up 7 votes
/**
 * Transfers file from a user's cloud "drive" to Filestack.
 *
 * @param providerName one of the static CLOUD constants in this class
 * @param options      storage options for how to save the file in Filestack
 * @return             new filelink
 * @throws HttpException on error response from backend
 * @throws IOException           on network failure
 */
@SuppressWarnings("ConstantConditions")
public FileLink storeCloudItem(String providerName, String path, StorageOptions options)
    throws IOException {

  if (options == null) {
    options = new StorageOptions.Builder().build();
  }

  JsonObject params = makeCloudParams(providerName, path);
  params.add("store", options.getAsJson());
  Response<JsonObject> response = Networking.getCloudService().store(params).execute();
  Util.checkResponseAndThrow(response);
  JsonElement responseJson = response.body().get(providerName);
  Gson gson = new Gson();
  CloudStoreResponse storeInfo = gson.fromJson(responseJson, CloudStoreResponse.class);
  return new FileLink(config, storeInfo.getHandle());
}
 
Example 2
Project: Yggdrasil   File: YggdrasilServiceTest.java   View Source Code Vote up 6 votes
@Test
public void testAuthenticate() {
    JsonObject payload = new JsonObject();
    payload.addProperty("username", "Notch");
    payload.addProperty("password", "password");

    JsonObject agent = new JsonObject();
    agent.addProperty("name", "Minecraft");
    agent.addProperty("version", 1);

    payload.add("agent", agent);

    CompletableFuture<JsonObject> result = service.authenticate(payload);
    CompletableFuture.allOf(result).join();

    JsonObject object = result.join();
    this.validateAuthenticate(object);
}
 
Example 3
Project: Backmemed   File: ServerStatusResponse.java   View Source Code Vote up 6 votes
public JsonElement serialize(ServerStatusResponse.Players p_serialize_1_, Type p_serialize_2_, JsonSerializationContext p_serialize_3_)
{
    JsonObject jsonobject = new JsonObject();
    jsonobject.addProperty("max", (Number)Integer.valueOf(p_serialize_1_.getMaxPlayers()));
    jsonobject.addProperty("online", (Number)Integer.valueOf(p_serialize_1_.getOnlinePlayerCount()));

    if (p_serialize_1_.getPlayers() != null && p_serialize_1_.getPlayers().length > 0)
    {
        JsonArray jsonarray = new JsonArray();

        for (int i = 0; i < p_serialize_1_.getPlayers().length; ++i)
        {
            JsonObject jsonobject1 = new JsonObject();
            UUID uuid = p_serialize_1_.getPlayers()[i].getId();
            jsonobject1.addProperty("id", uuid == null ? "" : uuid.toString());
            jsonobject1.addProperty("name", p_serialize_1_.getPlayers()[i].getName());
            jsonarray.add(jsonobject1);
        }

        jsonobject.add("sample", jsonarray);
    }

    return jsonobject;
}
 
Example 4
Project: SayNoToMcLeaks   File: Metrics.java   View Source Code Vote up 6 votes
protected JsonObject getRequestJsonObject(Logger logger, boolean logFailedRequests) {
    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) {
            logger.log(Level.WARNING, "Failed to get data for custom chart with id " + chartId, t);
        }
        return null;
    }
    return chart;
}
 
Example 5
Project: Backmemed   File: EnchantRandomly.java   View Source Code Vote up 6 votes
public void serialize(JsonObject object, EnchantRandomly functionClazz, JsonSerializationContext serializationContext)
{
    if (!functionClazz.enchantments.isEmpty())
    {
        JsonArray jsonarray = new JsonArray();

        for (Enchantment enchantment : functionClazz.enchantments)
        {
            ResourceLocation resourcelocation = (ResourceLocation)Enchantment.REGISTRY.getNameForObject(enchantment);

            if (resourcelocation == null)
            {
                throw new IllegalArgumentException("Don\'t know how to serialize enchantment " + enchantment);
            }

            jsonarray.add(new JsonPrimitive(resourcelocation.toString()));
        }

        object.add("enchantments", jsonarray);
    }
}
 
Example 6
Project: graphflow   File: Subgraphs.java   View Source Code Vote up 5 votes
@Override
public JsonObject toJson() {

    JsonObject vertexMap = new JsonObject();
    for (String variable : variableIndices.keySet()) {
        vertexMap.addProperty(variable, variableIndices.get(variable));
    }

    JsonObject vertexData = new JsonObject();
    for (int vertexId : vertices.keySet()) {
        vertexData.add(String.valueOf(vertexId), vertices.get(vertexId).toJson());
    }

    JsonObject edgeData = new JsonObject();
    for (long edgeId : edges.keySet()) {
        edgeData.add(String.valueOf(edgeId), edges.get(edgeId).toJson());
    }

    JsonArray subgraphsResult = new JsonArray();
    for (Subgraph subgraph : subgraphs) {
        subgraphsResult.add(subgraph.toJson());
    }

    JsonObject result = new JsonObject();
    result.addProperty(JsonKeyConstants.RESPONSE_TYPE.toString(),
        ResultType.SUBGRAPHS.toString());
    result.add(JsonKeyConstants.VERTEX_MAP.toString(), vertexMap);
    result.add(JsonKeyConstants.VERTICES.toString(), vertexData);
    result.add(JsonKeyConstants.EDGES.toString(), edgeData);
    result.add(JsonKeyConstants.SUBGRAPHS.toString(), subgraphsResult);
    addExecutionTimeToJson(result);
    return result;
}
 
Example 7
Project: SOS-The-Healthcare-Companion   File: ArrayRelationship.java   View Source Code Vote up 5 votes
public JsonElement toQCol() {
    JsonObject col = new JsonObject();
    col.add("name", new JsonPrimitive(this.columnName));
    col.add("columns", this.columns);
    if (this.whereExp != null)
        col.add("where", this.whereExp);
    if (this.limit != -1)
        col.add("limit", new JsonPrimitive(this.limit));
    if (this.offset != -1)
        col.add("offset", new JsonPrimitive(this.offset));
    if (this.orderByCols.size() > 0)
        col.add("order_by", this.orderByCols);
    return col;
}
 
Example 8
Project: raven   File: WinphoneNotification.java   View Source Code Vote up 5 votes
@Override
public JsonElement toJSON() {
    JsonObject json = super.toJSON().getAsJsonObject();
    
    if (null != title) {
        json.add(TITLE, new JsonPrimitive(title));
    }
    if (null != openPage) {
        json.add(_OPEN_PAGE, new JsonPrimitive(openPage));
    }
    
    return json;
}
 
Example 9
Project: mapbox-events-android   File: FeedbackEventSerializer.java   View Source Code Vote up 5 votes
private void serializeFeedbackData(NavigationFeedbackEvent src, JsonSerializationContext context,
                                   JsonObject feedbackEvent) {
  JsonObject feedbackData = context.serialize(src.getFeedbackData()).getAsJsonObject();
  for (Map.Entry<String, JsonElement> e : feedbackData.entrySet()) {
    feedbackEvent.add(e.getKey(), e.getValue());
  }
}
 
Example 10
Project: Mods   File: RandomWeaponFunction.java   View Source Code Vote up 5 votes
@Override
public void serialize(JsonObject object, RandomWeaponFunction functionClazz,
		JsonSerializationContext serializationContext) {
	object.add("upgrade_range", serializationContext.serialize(functionClazz.upgradeRange));
	object.add("valve_chance", serializationContext.serialize(functionClazz.valveWepChance));
	// object.add("possibleValues",
	// serializationContext.serialize(functionClazz.possibleValues));
	// object.add("data",
	// serializationContext.serialize(functionClazz.metaRange));
}
 
Example 11
Project: CTUConference   File: MessageSenderImpl.java   View Source Code Vote up 5 votes
public void sendCustomMessage(UserSession userSession, SocketMessageDTO message) throws IOException {
	Object outputData = message.getData();
	JsonObject jsonMessage = new JsonObject();
	jsonMessage.addProperty("type", message.getType());
	if(outputData != null) {
		if(outputData instanceof JsonObject) {
			jsonMessage.add("data", (JsonObject) outputData);
		} else {
			JsonElement data = gson.toJsonTree(outputData);
			jsonMessage.add("data", data);
		}
	}
	sendMessage(userSession, jsonMessage);
}
 
Example 12
Project: bStats-Metrics   File: MetricsLite.java   View Source Code Vote up 5 votes
/**
 * Collects the data and sends it afterwards.
 */
private void submitData() {
    final JsonObject data = getServerData();

    final JsonArray pluginData = new JsonArray();
    // Search for all other bStats Metrics classes to get their plugin data
    for (Object metrics : knownMetricsInstances) {
        try {
            Object plugin = metrics.getClass().getMethod("getPluginData").invoke(metrics);
            if (plugin instanceof JsonObject) {
                pluginData.add((JsonObject) plugin);
            }
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { }
    }

    data.add("plugins", pluginData);

    try {
        // Send the data
        sendData(data);
    } catch (Exception e) {
        // Something went wrong! :(
        if (logFailedRequests) {
            plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats!", e);
        }
    }
}
 
Example 13
Project: TruenoNPC   File: TruenoNPC_v1_8_r3.java   View Source Code Vote up 5 votes
private void cacheSkin(SkinData skindata){
    JsonObject jsonFile = getChacheFile(plugin);
    JsonArray newskindata = new JsonArray();
    if(jsonFile!=null){
        JsonArray oldskindata = jsonFile.getAsJsonArray("skindata");
        Iterator it = oldskindata.iterator();
        while(it.hasNext()){
            JsonElement element = (JsonElement) it.next();
            if(element.getAsJsonObject().get("id").getAsInt()==this.npcid){
                // element.getAsJsonObject().remove("value");
                //element.getAsJsonObject().remove("signature");
                //element.getAsJsonObject().addProperty("value", skindata.getValue());
                //element.getAsJsonObject().addProperty("signature", skindata.getSignature());
            }else {
                newskindata.add(element);
            }
        }
    }
    JsonObject skin = new JsonObject();
    skin.addProperty("id", this.npcid);
    skin.addProperty("value", skindata.getValue());
    skin.addProperty("signature", skindata.getSignature());
    newskindata.add(skin);

    JsonObject obj = new JsonObject();
    obj.add("skindata", newskindata);
    try {
        plugin.getDataFolder().mkdir();
        File file = new File(plugin.getDataFolder().getPath()+"/truenonpcdata.json");
        file.createNewFile();
        FileWriter writer = new FileWriter(file);
        writer.write(obj.toString());
        writer.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 14
Project: Wechat-Group   File: WxMpQrcodeServiceImpl.java   View Source Code Vote up 5 votes
@Override
public WxMpQrCodeTicket qrCodeCreateTmpTicket(int sceneId, Integer expireSeconds) throws WxErrorException {
  if (sceneId == 0) {
    throw new WxErrorException(WxError.newBuilder().setErrorCode(-1).setErrorMsg("临时二维码场景值不能为0!").build());
  }

  //expireSeconds 该二维码有效时间,以秒为单位。 最大不超过2592000(即30天),此字段如果不填,则默认有效期为30秒。
  if (expireSeconds != null && expireSeconds > 2592000) {
    throw new WxErrorException(WxError.newBuilder().setErrorCode(-1)
      .setErrorMsg("临时二维码有效时间最大不能超过2592000(即30天)!").build());
  }

  if (expireSeconds == null) {
    expireSeconds = 30;
  }

  String url = API_URL_PREFIX + "/create";
  JsonObject json = new JsonObject();
  json.addProperty("action_name", "QR_SCENE");
  if (expireSeconds != null) {
    json.addProperty("expire_seconds", expireSeconds);
  }
  JsonObject actionInfo = new JsonObject();
  JsonObject scene = new JsonObject();
  scene.addProperty("scene_id", sceneId);
  actionInfo.add("scene", scene);
  json.add("action_info", actionInfo);
  String responseContent = this.wxMpService.post(url, json.toString());
  return WxMpQrCodeTicket.fromJson(responseContent);
}
 
Example 15
Project: buckaroo   File: RecipeSerializer.java   View Source Code Vote up 5 votes
@Override
public JsonElement serialize(final Recipe recipe, final Type type, final JsonSerializationContext context) {

    Preconditions.checkNotNull(recipe);
    Preconditions.checkNotNull(type);
    Preconditions.checkNotNull(context);

    final JsonObject jsonObject = new JsonObject();

    jsonObject.add("name", context.serialize(recipe.name));
    jsonObject.addProperty("url", recipe.url.toString());
    jsonObject.add("versions", context.serialize(recipe.versions));

    return jsonObject;
}
 
Example 16
Project: BASS   File: WsPackage.java   View Source Code Vote up 5 votes
private JsonObject makeJson() {
    JsonObject paeckli = new JsonObject();

    paeckli.addProperty("resource", resource.toString().toLowerCase());
    paeckli.addProperty("action", action.toString().toLowerCase());
    paeckli.add("data", data);

    return paeckli;
}
 
Example 17
Project: mxisd   File: JsonUtils.java   View Source Code Vote up 4 votes
public static JsonObject getObj(Gson gson, String property, Object value) {
    JsonObject obj = new JsonObject();
    obj.add(property, gson.toJsonTree(value));
    return obj;
}
 
Example 18
Project: logviewer   File: GistCreator.java   View Source Code Vote up 4 votes
/**
 * Returns the json for creating gist
 */
private String getCreateGistJson(String content) {

    JsonObject gistObject = new JsonObject();
    gistObject.addProperty("description", "Shared log using Log Viewer  - https://josesamuel.com/logviewer/");

    JsonObject logDataObject = new JsonObject();
    logDataObject.addProperty("content", content);

    JsonObject fileDataObject = new JsonObject();
    fileDataObject.add("log", logDataObject);

    gistObject.add("files", fileDataObject);

    return gistObject.toString();
}
 
Example 19
Project: BaseClient   File: PlayerItemParser.java   View Source Code Vote up 4 votes
public static PlayerItemModel parseItemModel(JsonObject p_parseItemModel_0_)
{
    String s = Json.getString(p_parseItemModel_0_, "type");

    if (!Config.equals(s, "PlayerItem"))
    {
        throw new JsonParseException("Unknown model type: " + s);
    }
    else
    {
        int[] aint = Json.parseIntArray(p_parseItemModel_0_.get("textureSize"), 2);
        checkNull(aint, "Missing texture size");
        Dimension dimension = new Dimension(aint[0], aint[1]);
        boolean flag = Json.getBoolean(p_parseItemModel_0_, "usePlayerTexture", false);
        JsonArray jsonarray = (JsonArray)p_parseItemModel_0_.get("models");
        checkNull(jsonarray, "Missing elements");
        Map map = new HashMap();
        List list = new ArrayList();
        new ArrayList();

        for (int i = 0; i < jsonarray.size(); ++i)
        {
            JsonObject jsonobject = (JsonObject)jsonarray.get(i);
            String s1 = Json.getString(jsonobject, "baseId");

            if (s1 != null)
            {
                JsonObject jsonobject1 = (JsonObject)map.get(s1);

                if (jsonobject1 == null)
                {
                    Config.warn("BaseID not found: " + s1);
                    continue;
                }

                for (Entry<String, JsonElement> entry : jsonobject1.entrySet())
                {
                    if (!jsonobject.has((String)entry.getKey()))
                    {
                        jsonobject.add((String)entry.getKey(), (JsonElement)entry.getValue());
                    }
                }
            }

            String s2 = Json.getString(jsonobject, "id");

            if (s2 != null)
            {
                if (!map.containsKey(s2))
                {
                    map.put(s2, jsonobject);
                }
                else
                {
                    Config.warn("Duplicate model ID: " + s2);
                }
            }

            PlayerItemRenderer playeritemrenderer = parseItemRenderer(jsonobject, dimension);

            if (playeritemrenderer != null)
            {
                list.add(playeritemrenderer);
            }
        }

        PlayerItemRenderer[] aplayeritemrenderer = (PlayerItemRenderer[])((PlayerItemRenderer[])list.toArray(new PlayerItemRenderer[list.size()]));
        return new PlayerItemModel(dimension, flag, aplayeritemrenderer);
    }
}
 
Example 20
Project: Backmemed   File: EnchantWithLevels.java   View Source Code Vote up 4 votes
public void serialize(JsonObject object, EnchantWithLevels functionClazz, JsonSerializationContext serializationContext)
{
    object.add("levels", serializationContext.serialize(functionClazz.randomLevel));
    object.addProperty("treasure", Boolean.valueOf(functionClazz.isTreasure));
}