Example usage for com.google.gson JsonObject getAsJsonArray

List of usage examples for com.google.gson JsonObject getAsJsonArray

Introduction

In this page you can find the example usage for com.google.gson JsonObject getAsJsonArray.

Prototype

public JsonArray getAsJsonArray(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonArray.

Usage

From source file:me.gnat008.perworldinventory.data.serializers.DeprecatedMethodUtil.java

License:Open Source License

public static FireworkMeta getFireworkMeta(JsonObject json) {
    FireworkMeta dummy = (FireworkMeta) new ItemStack(Material.FIREWORK).getItemMeta();

    if (json.has("power"))
        dummy.setPower(json.get("power").getAsInt());
    else//from  ww  w .  j a v a  2 s  . c  o  m
        dummy.setPower(1);

    JsonArray effects = json.getAsJsonArray("effects");
    for (int i = 0; i < effects.size() - 1; i++) {
        JsonObject effectDto = effects.get(i).getAsJsonObject();
        FireworkEffect effect = getFireworkEffect(effectDto);
        if (effect != null)
            dummy.addEffect(effect);
    }
    return dummy;
}

From source file:me.gnat008.perworldinventory.data.serializers.DeprecatedMethodUtil.java

License:Open Source License

private static FireworkEffect getFireworkEffect(JsonObject json) {
    FireworkEffect.Builder builder = FireworkEffect.builder();

    //colors/* w w  w .  j av a2s .c om*/
    JsonArray colors = json.getAsJsonArray("colors");
    for (int j = 0; j < colors.size() - 1; j++) {
        builder.withColor(getColor(colors.get(j).getAsJsonObject()));
    }

    //fade colors
    JsonArray fadeColors = json.getAsJsonArray("fade-colors");
    for (int j = 0; j < fadeColors.size() - 1; j++) {
        builder.withFade(getColor(colors.get(j).getAsJsonObject()));
    }

    //hasFlicker
    if (json.get("flicker").getAsBoolean())
        builder.withFlicker();

    //trail
    if (json.get("trail").getAsBoolean())
        builder.withTrail();

    //type
    builder.with(FireworkEffect.Type.valueOf(json.get("type").getAsString()));

    return builder.build();
}

From source file:me.gnat008.perworldinventory.data.serializers.InventorySerializer.java

License:Open Source License

/**
 * Sets the Inventory using an ItemStack array constructed from a JsonObject.
 *
 * @param player The InventoryHolder to which the Inventory will be set
 * @param inv    The reference JsonArray
 * @param format Data format being used; 0 is old, 1 is new
 *//*from  w ww. j a va 2s. c  o m*/
public void setInventory(Player player, JsonObject inv, int format) {
    PlayerInventory inventory = player.getInventory();

    ItemStack[] armor = deserializeInventory(inv.getAsJsonArray("armor"), 4, format);
    ItemStack[] inventoryContents = deserializeInventory(inv.getAsJsonArray("inventory"), inventory.getSize(),
            format);

    inventory.clear();
    if (armor != null) {
        inventory.setArmorContents(armor);
    }

    if (inventoryContents != null) {
        inventory.setContents(inventoryContents);
    }

}

From source file:me.gnat008.perworldinventory.data.serializers.ItemSerializer.java

License:Open Source License

/**
 * Get an ItemStack from a JsonObject./*from   w w w  .j av  a2 s. c  om*/
 *
 * @param item The data for the item
 * @return The ItemStack
 * @deprecated Kept for compatibility reasons. Use ItemSerializer#deserializeItem(JsonObject data) whenever possible
 */
@Deprecated
public ItemStack getItem(JsonObject item) {
    int id = item.get("id").getAsInt();
    int amount = item.get("amount").getAsInt();
    short data = item.get("data").getAsShort();
    int repairPenalty = 0;

    String name = null;
    Map<Enchantment, Integer> enchants = null;
    ArrayList<String> flags = null;
    ArrayList<String> lore = null;

    if (item.has("name"))
        name = item.get("name").getAsString();
    if (item.has("enchantments"))
        enchants = DeprecatedMethodUtil.getEnchantments(item.get("enchantments").getAsString());
    if (item.has("flags")) {
        JsonArray f = item.getAsJsonArray("flags");
        flags = new ArrayList<>();
        for (int i = 0; i < f.size() - 1; i++)
            flags.add(f.get(i).getAsString());
    }
    if (item.has("lore")) {
        JsonArray l = item.getAsJsonArray("flags");
        lore = new ArrayList<>();
        for (int i = 0; i < l.size() - 1; i++)
            lore.add(l.get(i).getAsString());
    }
    if (item.has("repairPenalty"))
        repairPenalty = item.get("repairPenalty").getAsInt();

    Material mat = Material.getMaterial(id);
    ItemStack is = new ItemStack(mat, amount, data);

    if (mat == Material.BANNER) {
        BannerMeta meta = DeprecatedMethodUtil.getBannerMeta(item.getAsJsonObject("banner-meta"));
        is.setItemMeta(meta);
    } else if ((mat == Material.BOOK_AND_QUILL || mat == Material.WRITTEN_BOOK) && item.has("book-meta")) {
        BookMeta meta = DeprecatedMethodUtil.getBookMeta(item.getAsJsonObject("book-meta"));
        is.setItemMeta(meta);
    } else if (mat == Material.ENCHANTED_BOOK && item.has("book-meta")) {
        EnchantmentStorageMeta meta = DeprecatedMethodUtil
                .getEnchantedBookMeta(item.getAsJsonObject("book-meta"));
        is.setItemMeta(meta);
    } else if (DeprecatedMethodUtil.isLeatherArmor(mat) && item.has("armor-meta")) {
        LeatherArmorMeta meta = DeprecatedMethodUtil.getLeatherArmorMeta(item.getAsJsonObject("armor-meta"));
        is.setItemMeta(meta);
    } else if (mat == Material.SKULL_ITEM && item.has("skull-meta")) {
        SkullMeta meta = DeprecatedMethodUtil.getSkullMeta(item.getAsJsonObject("skull-meta"));
        is.setItemMeta(meta);
    } else if (mat == Material.FIREWORK && item.has("firework-meta")) {
        FireworkMeta meta = DeprecatedMethodUtil.getFireworkMeta(item.getAsJsonObject("firework-meta"));
        is.setItemMeta(meta);
    }

    ItemMeta meta = is.getItemMeta();
    if (name != null)
        meta.setDisplayName(name);
    if (flags != null) {
        for (String flag : flags) {
            meta.addItemFlags(ItemFlag.valueOf(flag));
        }
    }
    if (lore != null)
        meta.setLore(lore);
    is.setItemMeta(meta);
    if (repairPenalty != 0) {
        Repairable rep = (Repairable) meta;
        rep.setRepairCost(repairPenalty);
        is.setItemMeta((ItemMeta) rep);
    }

    if (enchants != null)
        is.addUnsafeEnchantments(enchants);
    return is;
}

From source file:me.gnat008.perworldinventory.data.serializers.PlayerSerializer.java

License:Open Source License

/**
 * Deserialize all aspects of a player, and apply their data. See {@link PlayerSerializer#serialize(PWIPlayer)}
 * for an explanation of the data format number.
 *
 * @param data   The saved player information.
 * @param player The Player to apply the deserialized information to.
 *///from  ww  w  .j a v  a  2s.co  m
public void deserialize(final JsonObject data, final Player player) {
    int format = 0;
    if (data.has("data-format"))
        format = data.get("data-format").getAsInt();

    if (settings.getProperty(PwiProperties.LOAD_ENDER_CHESTS) && data.has("ender-chest"))
        player.getEnderChest().setContents(inventorySerializer.deserializeInventory(
                data.getAsJsonArray("ender-chest"), player.getEnderChest().getSize(), format));
    if (settings.getProperty(PwiProperties.LOAD_INVENTORY) && data.has("inventory"))
        inventorySerializer.setInventory(player, data.getAsJsonObject("inventory"), format);
    if (data.has("stats"))
        statSerializer.deserialize(player, data.getAsJsonObject("stats"), format);
    if (settings.getProperty(PwiProperties.USE_ECONOMY)) {
        Economy econ = plugin.getEconomy();
        if (econ == null) {
            PwiLogger.warning("Economy saving is turned on, but no economy found!");
            return;
        }

        PwiLogger.debug("[ECON] Withdrawing " + econ.getBalance(player) + " from '" + player.getName() + "'!");
        EconomyResponse er = econ.withdrawPlayer(player, econ.getBalance(player));
        if (!er.transactionSuccess()) {
            PwiLogger.warning(
                    "[ECON] Unable to withdraw funds from '" + player.getName() + "': " + er.errorMessage);
        }

        PwiLogger.debug("[ECON] Withdrawing " + econ.bankBalance(player.getName()) + " from bank of '"
                + player.getName() + "'!");
        EconomyResponse bankER = econ.bankWithdraw(player.getName(), econ.bankBalance(player.getName()).amount);
        if (!bankER.transactionSuccess()) {
            PwiLogger.warning(
                    "[ECON] Unable to withdraw bank funds from '" + player.getName() + "': " + er.errorMessage);
        }

        if (data.has("economy") && er.transactionSuccess() && bankER.transactionSuccess()) {
            EconomySerializer.deserialize(econ, data.getAsJsonObject("economy"), player);
        }
    }
}

From source file:me.gnat008.perworldinventory.data.serializers.StatSerializer.java

License:Open Source License

/**
 * Apply stats to a player./* w w  w. ja v a  2s. c  o m*/
 *
 * @param player The Player to apply the stats to.
 * @param stats  The stats to apply.
 * @param dataFormat See {@link PlayerSerializer#serialize(PerWorldInventory, PWIPlayer)}.
 */
public void deserialize(Player player, JsonObject stats, int dataFormat) {
    if (settings.getProperty(PwiProperties.LOAD_CAN_FLY) && stats.has("can-fly"))
        player.setAllowFlight(stats.get("can-fly").getAsBoolean());
    if (settings.getProperty(PwiProperties.LOAD_DISPLAY_NAME) && stats.has("display-name"))
        player.setDisplayName(stats.get("display-name").getAsString());
    if (settings.getProperty(PwiProperties.LOAD_EXHAUSTION) && stats.has("exhaustion"))
        player.setExhaustion((float) stats.get("exhaustion").getAsDouble());
    if (settings.getProperty(PwiProperties.LOAD_EXP) && stats.has("exp"))
        player.setExp((float) stats.get("exp").getAsDouble());
    if (settings.getProperty(PwiProperties.LOAD_FLYING) && stats.has("flying"))
        player.setFlying(stats.get("flying").getAsBoolean());
    if (settings.getProperty(PwiProperties.LOAD_HUNGER) && stats.has("food"))
        player.setFoodLevel(stats.get("food").getAsInt());
    if (settings.getProperty(PwiProperties.LOAD_HEALTH) && stats.has("health")) {
        double health = stats.get("health").getAsDouble();
        if (health <= player.getMaxHealth()) {
            player.setHealth(health);
        } else if (health <= 0) {
            player.setHealth(player.getMaxHealth());
        } else {
            player.setHealth(player.getMaxHealth());
        }
    }
    if (settings.getProperty(PwiProperties.LOAD_GAMEMODE)
            && (!settings.getProperty(PwiProperties.SEPARATE_GAMEMODE_INVENTORIES)) && stats.has("gamemode")) {
        if (stats.get("gamemode").getAsString().length() > 1) {
            player.setGameMode(GameMode.valueOf(stats.get("gamemode").getAsString()));
        } else {
            int gm = stats.get("gamemode").getAsInt();
            switch (gm) {
            case 0:
                player.setGameMode(GameMode.CREATIVE);
                break;
            case 1:
                player.setGameMode(GameMode.SURVIVAL);
                break;
            case 2:
                player.setGameMode(GameMode.ADVENTURE);
                break;
            case 3:
                player.setGameMode(GameMode.SPECTATOR);
                break;
            }
        }
    }
    if (settings.getProperty(PwiProperties.LOAD_LEVEL) && stats.has("level"))
        player.setLevel(stats.get("level").getAsInt());
    if (settings.getProperty(PwiProperties.LOAD_POTION_EFFECTS) && stats.has("potion-effects")) {
        if (dataFormat < 2) {
            PotionEffectSerializer.setPotionEffects(stats.get("potion-effects").getAsString(), player);
        } else {
            PotionEffectSerializer.setPotionEffects(stats.getAsJsonArray("potion-effects"), player);
        }
    }
    if (settings.getProperty(PwiProperties.LOAD_SATURATION) && stats.has("saturation"))
        player.setSaturation((float) stats.get("saturation").getAsDouble());
    if (settings.getProperty(PwiProperties.LOAD_FALL_DISTANCE) && stats.has("fallDistance"))
        player.setFallDistance(stats.get("fallDistance").getAsFloat());
    if (settings.getProperty(PwiProperties.LOAD_FIRE_TICKS) && stats.has("fireTicks"))
        player.setFireTicks(stats.get("fireTicks").getAsInt());
    if (settings.getProperty(PwiProperties.LOAD_MAX_AIR) && stats.has("maxAir"))
        player.setMaximumAir(stats.get("maxAir").getAsInt());
    if (settings.getProperty(PwiProperties.LOAD_REMAINING_AIR) && stats.has("remainingAir"))
        player.setRemainingAir(stats.get("remainingAir").getAsInt());
}

From source file:me.ixfan.wechatkit.message.MessageManager.java

License:Open Source License

/**
 * ?????/*from   w  w  w. java2 s. c om*/
 * @return ????
 * @throws WeChatApiErrorException API??
 */
public List<MessageTemplate> retrieveMessageTemplates() throws WeChatApiErrorException {
    final String url = WeChatConstants.WECHAT_GET_MESSAGE_TEMPLATES.replace("${ACCESS_TOKEN}",
            super.tokenManager.getAccessToken());
    JsonObject jsonResponse;
    try {
        jsonResponse = HttpClientUtil.sendGetRequestAndGetJsonResponse(url);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (!jsonResponse.has("template_list")) {
        throw new WeChatApiErrorException(jsonResponse.get("errcode").getAsInt(),
                jsonResponse.get("errmsg").getAsString());
    } else {
        JsonArray teplArray = jsonResponse.getAsJsonArray("template_list");
        if (teplArray.size() == 0) {
            return Collections.emptyList();
        }
        Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .create();
        return gson.fromJson(teplArray, new TypeToken<ArrayList<MessageTemplate>>() {
        }.getType());
    }

}

From source file:me.ixfan.wechatkit.user.UserManager.java

License:Open Source License

/**
 * ?//www  .j  av a 2  s.c o m
 *
 * @return 
 * @throws WeChatApiErrorException API??
 */
public List<UserTag> getExistingTags() throws WeChatApiErrorException {
    final String url = WeChatConstants.WECHAT_GET_GET_TAGS.replace("${ACCESS_TOKEN}",
            super.tokenManager.getAccessToken());
    JsonObject jsonResp;
    try {
        jsonResp = HttpClientUtil.sendGetRequestAndGetJsonResponse(url);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (jsonResp.has("tags")) {
        Gson gson = new Gson();
        return Arrays.asList(gson.fromJson(jsonResp.getAsJsonArray("tags"), UserTag[].class));
    } else {
        throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(),
                jsonResp.get("errmsg").getAsString());
    }
}

From source file:me.ixfan.wechatkit.user.UserManager.java

License:Open Source License

/**
 * ?/* w  ww  .  j ava2s  .  c om*/
 *
 * @param openId ?OpenID
 * @return ID
 * @throws WeChatApiErrorException API??
 */
public int[] getTagsOfUser(String openId) throws WeChatApiErrorException {
    Args.notEmpty(openId, "OpenID");

    final String url = WeChatConstants.WECHAT_POST_GET_TAGS_OF_USER.replace("${ACCESS_TOKEN}",
            super.tokenManager.getAccessToken());
    final String jsonData = "{\"openid\":\"${OPENID}\"}";
    JsonObject jsonResp;
    try {
        jsonResp = HttpClientUtil.sendPostRequestWithJsonBody(url, jsonData.replace("${OPENID}", openId));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (jsonResp.has("tagid_list")) {
        JsonArray jsonArray = jsonResp.getAsJsonArray("tagid_list");
        int[] tagIds = new int[jsonArray.size()];
        if (jsonArray.size() > 0) {
            IntStream.range(0, jsonArray.size()).forEach(i -> tagIds[i] = jsonArray.get(i).getAsInt());
        }
        return tagIds;
    } else {
        throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(),
                jsonResp.get("errmsg").getAsString());
    }
}

From source file:me.jamiemansfield.mc.text.serialiser.JsonTextSerialiser.java

License:MIT License

@Override
public Text deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (!json.isJsonObject()) {
        throw new JsonParseException("Terribly sorry, but I will not be able to deserialise " + json);
    }/*from w  w w  . j av  a 2s  . co  m*/
    final JsonObject obj = json.getAsJsonObject();
    final Text.Builder text;

    if (obj.has("text")) {
        text = Text.builder(obj.get("text").getAsString());
    } else if (obj.has("translate")) {
        if (obj.has("with") && obj.get("with").isJsonArray()) {
            final JsonArray with = obj.getAsJsonArray("with");
            final Text[] arguments = new Text[with.size()];

            for (int i = 0; i < with.size(); i++) {
                final JsonElement element = with.get(i);
                arguments[i] = this.deserialize(element, element.getClass(), context);
            }

            text = Text.translatableBuilder(obj.get("translate").getAsString(), arguments);
        } else {
            text = Text.translatableBuilder(obj.get("translate").getAsString());
        }
    } else {
        throw new JsonParseException("Terribly sorry, but I will not be able to deserialise " + json);
    }

    DECORATION.getEntries().stream().filter(decoration -> obj.has(decoration.getInternalName())).forEach(
            decoration -> text.apply(decoration, obj.get(decoration.getInternalName()).getAsBoolean()));

    if (obj.has("color")) {
        final Optional<TextColour> colour = COLOUR.getEntries().stream()
                .filter(clr -> clr.getInternalName().equals(obj.get("color").getAsString())).findAny();
        if (!colour.isPresent()) {
            throw new JsonParseException("Terribly sorry, but I will not be able to deserialise " + json);
        }
        text.apply(colour.get());
    }

    if (obj.has("insertion")) {
        text.insertion(obj.get("insertion").getAsString());
    }

    if (obj.has("clickEvent")) {
        final Optional<ClickEvent.Action> action = CLICK_EVENT_ACTION.getEntries().stream().filter(a -> obj
                .get("clickEvent").getAsJsonObject().get("action").getAsString().equals(a.getInternalName()))
                .findAny();
        if (!action.isPresent()) {
            throw new JsonParseException("Terribly sorry, but I will not be able to deserialise " + json);
        }
        final JsonElement element = obj.get("clickEvent").getAsJsonObject().get("value");
        text.click(new ClickEvent(action.get(), this.deserialize(element, element.getClass(), context)));
    }

    if (obj.has("hoverEvent")) {
        final Optional<HoverEvent.Action> action = HOVER_EVENT_ACTION.getEntries().stream().filter(a -> obj
                .get("hoverEvent").getAsJsonObject().get("action").getAsString().equals(a.getInternalName()))
                .findAny();
        if (!action.isPresent()) {
            throw new JsonParseException("Terribly sorry, but I will not be able to deserialise " + json);
        }
        final JsonElement element = obj.get("hoverEvent").getAsJsonObject().get("value");
        text.hover(new HoverEvent(action.get(), this.deserialize(element, element.getClass(), context)));
    }

    if (obj.has("extra")) {
        final JsonArray extra = obj.getAsJsonArray("extra");

        for (int i = 0; i < extra.size(); i++) {
            final JsonElement element = extra.get(i);
            text.append(this.deserialize(element, element.getClass(), context));
        }
    }

    return text.build();
}