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:com.headswilllol.mineflat.world.SaveManager.java

License:Open Source License

public static Chunk loadChunk(Level level, int chunk) {
    JsonObject jChunk = level.getWorld().getJson().getAsJsonObject("levels")
            .getAsJsonObject(Integer.toString(level.getIndex())).getAsJsonObject("chunks")
            .getAsJsonObject(Integer.toString(chunk));
    if (jChunk != null) {
        System.out.println("Loading chunk " + chunk);
        Biome biome = Biome.getById(jChunk.get("biome").toString());
        Chunk c = new Chunk(level, chunk, biome);
        for (JsonElement blockObj : jChunk.getAsJsonArray("blocks")) {
            JsonObject block = blockObj.getAsJsonObject();
            Material type = Material.valueOf(block.get("type").getAsString());
            if (type == null)
                type = Material.AIR;//  w  ww.j a  v  a 2 s .  c om
            int data = block.get("data") != null ? block.get("data").getAsInt() : 0;
            Block b = new Block(type, data,
                    new Location(level, Chunk.getWorldXFromChunkIndex(chunk, block.get("x").getAsLong()),
                            block.get("y").getAsLong()));
            JsonObject meta = (JsonObject) block.get("metadata");
            for (Map.Entry<String, JsonElement> e : meta.entrySet()) {
                JsonPrimitive prim = meta.get(e.getKey()).getAsJsonPrimitive();
                Object value;
                if (prim.isBoolean())
                    value = prim.getAsBoolean();
                else if (prim.isNumber())
                    value = prim.getAsNumber();
                else if (prim.isString())
                    value = prim.getAsString();
                else
                    value = prim.getAsCharacter();
                b.setMetadata(e.getKey(), value);
            }
            b.addToWorld();
        }
        for (Object entityObj : jChunk.get("entities").getAsJsonArray()) {
            JsonObject entity = (JsonObject) entityObj;
            EntityType type = EntityType.valueOf(entity.get("type").getAsString());
            float x = Chunk.getWorldXFromChunkIndex(c.getIndex(),
                    Float.valueOf(Double.toString(entity.get("x").getAsDouble())));
            float y = Float.valueOf(Double.toString(entity.get("y").getAsDouble()));
            float w = Float.valueOf(Double.toString(entity.get("w").getAsDouble()));
            float h = Float.valueOf(Double.toString(entity.get("h").getAsDouble()));
            Entity e;
            if (entity.has("living")) {
                if (entity.has("mob")) {
                    switch (type) {
                    case GHOST:
                        e = new Ghost(new Location(level, x, y));
                        break;
                    case SNAIL:
                        e = new Snail(new Location(level, x, y));
                        break;
                    default:
                        continue; // ignore it
                    }
                    ((Mob) e).setPlannedWalkDistance(entity.get("pwd").getAsFloat());
                    ((Mob) e).setActualWalkDistance(entity.get("awd").getAsFloat());
                    ((Mob) e).setLastX(entity.get("lx").getAsFloat());
                } else {
                    switch (type) {
                    case PLAYER:
                        e = new Player(new Location(level, x, y));
                        break;
                    case HUMAN:
                        e = new Human(new Location(level, x, y));
                        break;
                    default:
                        continue; // ignore it
                    }
                }
                ((Living) e).setFacingDirection(Direction.valueOf(entity.get("fd").getAsString()));
                ((Living) e).setJumping(entity.get("j").getAsBoolean());
            } else
                e = new Entity(type, new Location(level, x, y), w, h);
            e.getVelocity().setX(Float.valueOf(Double.toString(entity.get("xv").getAsDouble())));
            e.getVelocity().setY(Float.valueOf(Double.toString(entity.get("yv").getAsDouble())));
            level.addEntity(e);
            if (type == EntityType.PLAYER)
                Main.player = (Player) e;
        }
        c.updateLight();
        Chunk left = c.getLevel().getChunk(c.getIndex() == 1 ? -1 : c.getIndex() - 1);
        Chunk right = c.getLevel().getChunk(c.getIndex() == -1 ? 1 : c.getIndex() + 1);
        if (left != null) {
            for (int y = 0; y < c.getLevel().getWorld().getChunkHeight(); y++) {
                left.getBlock(c.getLevel().getWorld().getChunkLength() - 1, y).updateLight();
                VboUtil.updateChunkArray(c.getLevel(), left.getIndex());
            }
        }
        if (right != null) {
            for (int y = 0; y < c.getLevel().getWorld().getChunkHeight(); y++) {
                right.getBlock(0, y).updateLight();
                VboUtil.updateChunkArray(c.getLevel(), right.getIndex());
            }
        }
        System.gc(); //TODO: temporary fix until I have the motivation to find the memory leak
        return c;
    }
    return null;
}

From source file:com.health.smart.ws.MobileAPI.java

@POST
@Path("/savemeasurement")
public Response saveMeasurement(String payload) {
    try {/*w w  w.ja v  a  2  s .  c  om*/
        JsonObject request = GsonHelper.fromString(payload);
        String token = request.getAsJsonPrimitive("token").getAsString();
        JsonArray mess = request.getAsJsonArray("measurements");
        int pid = sysEjb.validateToken(token);
        List<DayMeasurement> measurements = new ArrayList<>();
        for (int i = 0; i < mess.size(); i++) {
            DayMeasurement m = GsonHelper.fromJsonElement(mess.get(i), DayMeasurement.class);
            m.setPatientId(pid);
            measurements.add(m);
        }
        mongoEjb.saveDayMeasurement(measurements);
        JsonObject jObject = new JsonObject();
        jObject.addProperty("result", "success");
        return Response.status(200).entity(jObject.toString()).build();
    } catch (Exception e) {
        e.printStackTrace();
        return Response.status(500).entity(e.getMessage()).build();
    }
}

From source file:com.heroiclabs.sdk.android.util.json.MessageJsonDeserializer.java

License:Apache License

/** {@inheritDoc} */
@Override//from  w w w .  ja va 2 s  .  c  om
public Message deserialize(final @NonNull JsonElement json, final @NonNull Type typeOfT,
        final @NonNull JsonDeserializationContext context) throws JsonParseException {
    final JsonObject object = json.getAsJsonObject();
    final String messageId = object.get("message_id").getAsString();
    final List<String> tags;
    if (object.get("tags").isJsonNull()) {
        tags = null;
    } else {
        tags = new ArrayList<>();
        for (final JsonElement tag : object.getAsJsonArray("tags")) {
            tags.add(tag.getAsString());
        }
    }
    final String subject = object.get("subject").getAsString();
    final long createdAt = object.get("created_at").getAsLong();
    final long expiresAt = object.get("expires_at").getAsLong();
    final Long readAt = JsonDeserializerUtils.extractAsLong(object, "read_at");
    final String body = JsonDeserializerUtils.extractAsString(object, "body");

    return new Message(messageId, tags, subject, createdAt, expiresAt, readAt, body, codec);
}

From source file:com.ibasco.agql.core.AbstractWebApiInterface.java

License:Open Source License

/**
 * <p>A Utility function that retrieves the specified json element and converts it to a Parameterized {@link java.util.Collection} instance.</p>
 *
 * @param itemType        The {@link Class} type of the item in the {@link Collection}
 * @param searchKey       The name of the {@link JsonArray} element that we will convert
 * @param searchElement   The {@link JsonObject} that will be used to search for the {@link JsonArray} element
 * @param collectionClass A {@link Class} representing the concrete implementation of the {@link Collection}
 * @param strict          If <code>true</code> an exception will be thrown if the listName is not found within the search element specified. Otherwise no exceptions will be raised and an empty {@link Collection} instance will be returned.
 * @param <A>             The internal type of the {@link Collection} to be returned
 *
 * @return A {@link Collection} containing the type specified by collectionClass argument
 *//*from  w w w . j  a  v  a2 s . c  o  m*/
protected <A extends Collection> A asCollectionOf(Class itemType, String searchKey, JsonObject searchElement,
        Class<? extends Collection> collectionClass, boolean strict) {
    if (searchElement.has(searchKey) && searchElement.get(searchKey).isJsonArray()) {
        return fromJson(searchElement.getAsJsonArray(searchKey),
                new CollectionParameterizedType(itemType, collectionClass));
    }
    if (strict)
        throw new JsonElementNotFoundException(searchElement,
                String.format("Unable to find a JsonArray element '%s' from the search element", searchKey));
    else {
        return null;
    }
}

From source file:com.ibasco.agql.protocols.supercell.coc.webapi.interfaces.CocClans.java

License:Open Source License

/**
 * <p>//from   w  w w .j a v a  2  s . c  o  m
 * Search all clans by name and/or filtering the results using various criteria. At least one filtering criteria
 * must be defined and if name is used as part of search, it is required to be at least three characters long.
 * It is not possible to specify ordering for results so clients should not rely on any specific
 * ordering as that may change in the future releases of the API.
 * </p>
 *
 * @param criteria
 *         A {@link CocSearchCriteria} to help your life much easier
 *
 * @return A {@link CompletableFuture} containing a {@link List} of clans matching the criteria. Empty if no match
 * found.
 */
public CompletableFuture<List<CocClanDetailedInfo>> searchClans(CocSearchCriteria criteria) {
    CompletableFuture<JsonObject> json = sendRequest(new SearchClan(VERSION_1, criteria));
    return json.thenApply(new Function<JsonObject, List<CocClanDetailedInfo>>() {
        @Override
        public List<CocClanDetailedInfo> apply(JsonObject root) {
            JsonArray items = root.getAsJsonArray("items");
            Type type = new TypeToken<List<CocClanDetailedInfo>>() {
            }.getType();
            return builder().fromJson(items, type);
        }
    });
}

From source file:com.ibasco.agql.protocols.supercell.coc.webapi.interfaces.CocClans.java

License:Open Source License

/**
 * <p>List clan members</p>/*from  w  w  w.ja  va  2  s  . co  m*/
 *
 * @param clanTag
 *         A {@link String} representing the clan tag
 * @param limit
 *         An {@link Integer} limiting the number of records returned
 * @param after
 *         (optional) An {@link Integer} that indicates to return only items that occur after this marker.
 *         After
 *         marker can be found from the response, inside the 'paging' property. Note that only after
 *         or before can be specified for a request, not both. Otherwise use -1 to disregard.
 * @param before
 *         (optional) An {@link Integer} that indicates to return only items that occur before this marker.
 *         Before marker can be found from the response,
 *         inside the 'paging' property. Note that only after or before can be specified for a request, not
 *         both. Otherwise use -1 to disregard.
 *
 * @return A {@link CompletableFuture} returning an instance of {@link List} of type {@link CocPlayerBasicInfo}
 */
public CompletableFuture<List<CocPlayerBasicInfo>> getClanMembers(String clanTag, int limit, int after,
        int before) {
    CompletableFuture<JsonObject> json = sendRequest(
            new GetClanMembers(VERSION_1, clanTag, limit, after, before));
    return json.thenApply(new Function<JsonObject, List<CocPlayerBasicInfo>>() {
        @Override
        public List<CocPlayerBasicInfo> apply(JsonObject root) {
            JsonArray items = root.getAsJsonArray("items");
            Type type = new TypeToken<List<CocPlayerBasicInfo>>() {
            }.getType();
            return builder().fromJson(items, type);
        }
    });
}

From source file:com.ibasco.agql.protocols.supercell.coc.webapi.interfaces.CocClans.java

License:Open Source License

/**
 * <p>Retrieve clan's clan war log</p>
 *
 * @param clanTag/*from w w w.  j  av  a  2  s.c o m*/
 *         A {@link String} preceded by a hash tag '#' character
 * @param limit
 *         An {@link Integer} limiting the number of records returned
 * @param after
 *         (optional) An {@link Integer} that indicates to return only items that occur after this marker.
 *         After marker can be found from the response, inside the 'paging' property. Note
 *         that only after or before can be specified for a request, not both. Otherwise use
 *         -1 to disregard.
 * @param before
 *         (optional) An {@link Integer} that indicates to return only items that occur before this marker.
 *         Before marker can be found from the response, inside the 'paging' property. Note that only after
 *         or before can be specified for a request, not both.
 *         Otherwise use -1 to disregard.
 *
 * @return A {@link CompletableFuture} which contains a future result for a {@link List} of {@link CocWarLogEntry}
 */
public CompletableFuture<List<CocWarLogEntry>> getClanWarLog(String clanTag, int limit, int after, int before) {
    CompletableFuture<JsonObject> json = sendRequest(
            new GetClanWarLog(VERSION_1, clanTag, limit, after, before));
    return json.thenApply(new Function<JsonObject, List<CocWarLogEntry>>() {
        @Override
        public List<CocWarLogEntry> apply(JsonObject root) {
            JsonArray items = root.getAsJsonArray("items");
            Type type = new TypeToken<List<CocWarLogEntry>>() {
            }.getType();
            return builder().fromJson(items, type);
        }
    });
}

From source file:com.ibasco.agql.protocols.supercell.coc.webapi.interfaces.CocLeagues.java

License:Open Source License

/**
 * <p>Get list of leagues</p>
 *
 * @param limit/* w  w  w .  j  a v a 2  s .c  om*/
 *         An {@link Integer} limiting the number of records returned
 * @param before
 *         (optional) An {@link Integer} that indicates to return only items that occur before this marker.
 *         Before marker can be found from the response, inside the 'paging' property. Note that only after
 *         or before can be specified for a request, not both.
 *         Otherwise use -1 to disregard.
 * @param after
 *         (optional) An {@link Integer} that indicates to return only items that occur after this marker.
 *         After marker can be found from the response, inside the 'paging' property. Note
 *         that only after or before can be specified for a request, not both. Otherwise use
 *         -1 to disregard.
 *
 * @return A {@link CompletableFuture} which contains a future result for a {@link List} of {@link CocLeague}
 */
public CompletableFuture<List<CocLeague>> getLeagueList(int limit, int before, int after) {
    CompletableFuture<JsonObject> json = sendRequest(new GetLeagues(VERSION_1, limit, before, after));
    return json.thenApply(new Function<JsonObject, List<CocLeague>>() {
        @Override
        public List<CocLeague> apply(JsonObject root) {
            return builder().fromJson(root.getAsJsonArray("items"), CocTypes.COC_LIST_LEAGUE);
        }
    });
}

From source file:com.ibasco.agql.protocols.supercell.coc.webapi.interfaces.CocLeagues.java

License:Open Source License

/**
 * <p>Get league seasons. Note that league season information is available only for Legend League.</p>
 *
 * @param leagueId//from  ww w.j  a  v  a  2 s .  c  om
 *         An {@link Integer} representing a valid Clash of Clans League Id
 * @param limit
 *         An {@link Integer} limiting the number of records returned
 * @param before
 *         (optional) An {@link Integer} that indicates to return only items that occur before this marker.
 *         Before marker can be found from the response, inside the 'paging' property. Note
 *         that only after or before can be specified for a request, not both. Otherwise use -1 to disregard.
 * @param after
 *         (optional) An {@link Integer} that indicates to return only items that occur after this marker.
 *         After marker can be found from the response, inside the 'paging' property. Note that only after
 *         or before can be specified for a request, not both. Otherwise use -1 to disregard.
 *
 * @return A {@link CompletableFuture} containing a future result for a {@link List} of {@link CocLeagueSeason}
 */
public CompletableFuture<List<CocLeagueSeason>> getLeagueSeasons(int leagueId, int limit, int before,
        int after) {
    CompletableFuture<JsonObject> json = sendRequest(
            new GetLeagueSeasons(VERSION_1, leagueId, limit, before, after));
    return json.thenApply(new Function<JsonObject, List<CocLeagueSeason>>() {
        @Override
        public List<CocLeagueSeason> apply(JsonObject root) {
            JsonArray items = root.getAsJsonArray("items");
            return builder().fromJson(items, new TypeToken<List<CocLeagueSeason>>() {
            }.getType());
        }
    });
}

From source file:com.ibasco.agql.protocols.supercell.coc.webapi.interfaces.CocLeagues.java

License:Open Source License

/**
 * <p>Get league season player rankings. Note that league season information is available only for Legend
 * League.</p>//from   w  w  w  . j  a  v a  2s .co m
 *
 * @param leagueId
 *         An {@link Integer} representing a valid Clash of Clans League Id
 * @param seasonId
 *         An {@link Integer} representing a valid Clash of Clans Season Id
 * @param limit
 *         An {@link Integer} limiting the number of records returned
 * @param before
 *         (optional) An {@link Integer} that indicates to return only items that occur before this marker.
 *         Before marker can be found from the response, inside the 'paging' property. Note         that only after
 *         or before can be specified for a request, not both. Otherwise use -1 to disregard.
 * @param after
 *         (optional) An {@link Integer} that indicates to return only items that occur after this marker.
 *         After marker can be found from the response, inside the 'paging' property. Note that only after
 *         or before can be specified for a request, not both. Otherwise use -1 to disregard.
 *
 * @return A {@link CompletableFuture} containing a future result for a {@link List} of {@link CocPlayerRankInfo}
 *
 * @see CocLeagues#getLeagueSeasons(int)
 */
public CompletableFuture<List<CocPlayerRankInfo>> getLeagueSeasonsPlayerRankings(int leagueId, String seasonId,
        int limit, int before, int after) {
    CompletableFuture<JsonObject> json = sendRequest(
            new GetLeagueSeasonRankings(VERSION_1, leagueId, seasonId, limit, before, after));
    return json.thenApply(new Function<JsonObject, List<CocPlayerRankInfo>>() {
        @Override
        public List<CocPlayerRankInfo> apply(JsonObject root) {
            JsonArray items = root.getAsJsonArray("items");
            return builder().fromJson(items, CocTypes.COC_LIST_PLAYER_RANK_INFO);
        }
    });
}