Example usage for com.google.gson JsonElement getAsJsonArray

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

Introduction

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

Prototype

public JsonArray getAsJsonArray() 

Source Link

Document

convenience method to get this element as a JsonArray .

Usage

From source file:com.janssen.games.ical.GamesCalenderController.java

License:Apache License

/**
 *
 * @param teamId//from   w  ww.  j  av a2s  .  c  om
 * @return
 * @throws IOException
 * @throws ParseException
 */
private List<Game> getGames(final String teamId) throws IOException, ParseException {

    List<Game> games = new ArrayList<>();

    final Document doc = Jsoup.connect(VBL_URL + teamId).timeout(5000).method(Connection.Method.GET)
            .ignoreContentType(true).execute().parse();

    final JsonElement parse = new JsonParser().parse(doc.text());
    final JsonArray asJsonArray = parse.getAsJsonArray();
    final long now = new Date().getTime();

    for (int i = 0; i < asJsonArray.size(); i++) {
        final JsonObject game = asJsonArray.get(i).getAsJsonObject();

        final long gameDate = game.get("jsDTCode").getAsLong();
        if (gameDate < now) {
            continue;
        }

        final String beginTijd = game.get("beginTijd").getAsString();
        if (beginTijd.trim().length() == 0) {
            continue;
        }

        final String wedID = game.get("wedID").getAsString();
        final String thuisNaam = game.get("tTNaam").getAsString();
        final String uitNaam = game.get("tUNaam").getAsString();
        final String accomodatie = game.get("accNaam").getAsString();
        final String pouleNaam = game.get("pouleNaam").getAsString();

        games.add(new Game(wedID, thuisNaam, uitNaam, gameDate, accomodatie, pouleNaam));
    }

    return games;
}

From source file:com.jcwhatever.nucleus.storage.JsonDataNode.java

License:MIT License

@Override
@Nullable//ww w  .j  a v  a 2 s  .c o  m
protected Object getCollectionObject(String keyPath) {
    JsonElement element = getJsonElement(keyPath);
    if (element == null || element.isJsonObject() || !element.isJsonArray())
        return null;

    JsonArray array = element.getAsJsonArray();
    List<String> result = new ArrayList<>(array.size());

    for (int i = 0; i < array.size(); i++) {
        result.add(array.get(i).getAsString());
    }

    return result;
}

From source file:com.jeremyfeinstein.slidingmenu.example.StorageService.java

License:Apache License

/***
 * Gets all of the containers from storage
 *//* w  ww  .  j a  va2s .c  o m*/
public void getContainers() {
    mTableContainers.where().execute(new TableJsonQueryCallback() {
        @Override
        public void onCompleted(JsonElement result, int count, Exception exception,
                ServiceFilterResponse response) {
            if (exception != null) {
                Log.e(TAG, exception.getCause().getMessage());
                return;
            }
            //Loop through and build an array of container names
            JsonArray results = result.getAsJsonArray();
            mContainers = new ArrayList<Map<String, String>>();
            for (int i = 0; i < results.size(); i++) {
                JsonElement item = results.get(i);
                Map<String, String> map = new HashMap<String, String>();
                map.put("ContainerName", item.getAsJsonObject().getAsJsonPrimitive("name").getAsString());
                mContainers.add(map);
            }
            //Broadcast that the containers have been loaded
            Intent broadcast = new Intent();
            broadcast.setAction("containers.loaded");
            mContext.sendBroadcast(broadcast);
        }
    });
}

From source file:com.jeremyfeinstein.slidingmenu.example.StorageService.java

License:Apache License

/***
 * Get all of the blobs for a container//www .  j a  v  a  2s. c o  m
 * @param containerName
 */
public void getBlobsForContainer(String containerName) {
    //Pass the container name as a parameter
    //We have to do it in this way for it to show up properly on the server
    mTableBlobs.execute(mTableBlobs.parameter("container", containerName), new TableJsonQueryCallback() {
        @Override
        public void onCompleted(JsonElement result, int count, Exception exception,
                ServiceFilterResponse response) {
            if (exception != null) {
                Log.e(TAG, exception.getCause().getMessage());
                return;
            }
            JsonArray results = result.getAsJsonArray();
            //Store a local array of both the JsonElements and the blob names
            mBlobNames = new ArrayList<Map<String, String>>();
            mBlobObjects = new ArrayList<JsonElement>();
            for (int i = 0; i < results.size(); i++) {
                JsonElement item = results.get(i);
                mBlobObjects.add(item);
                Map<String, String> map = new HashMap<String, String>();
                map.put("BlobName", item.getAsJsonObject().getAsJsonPrimitive("name").getAsString());
                mBlobNames.add(map);
            }
            //Broadcast that blobs are loaded
            Intent broadcast = new Intent();
            broadcast.setAction("blobs.loaded");
            mContext.sendBroadcast(broadcast);
        }
    });
}

From source file:com.jomofisher.tests.cmake.JsonUtils.java

License:Apache License

private static void checkJsonElementAgainstJavaType(JsonElement element, Class clazz) {
    if (element.isJsonArray()) {
        checkJsonArrayAgainstJavaType(element.getAsJsonArray(), clazz);
    } else if (element.isJsonObject()) {
        checkJsonObjectAgainstJavaType(element.getAsJsonObject(), clazz);
    }/*from  w  w w  . ja v  a2s  .co  m*/
}

From source file:com.jomofisher.tests.cmake.JsonUtils.java

License:Apache License

private static void checkJsonElementAgainstJava(JsonElement element, Field field) {
    if (element.isJsonArray()) {
        checkJsonArrayAgainstJava(element.getAsJsonArray(), field);
    } else if (element.isJsonObject()) {
        checkJsonObjectAgainstJava(element.getAsJsonObject(), field);
    }//from w  w w . j a v a2 s .co m
}

From source file:com.kagilum.intellij.icescrum.IceScrumRepository.java

License:Apache License

@Override
public Task[] getIssues(@Nullable String s, int i, long l) throws Exception {
    String url = createCompleteUrl();
    GetMethod method = new GetMethod(url);
    configureHttpMethod(method);//w ww  . j  a  v  a  2s  . c o  m
    method.setRequestHeader("Content-type", "text/json");

    getHttpClient().executeMethod(method);
    int code = method.getStatusCode();
    if (code != HttpStatus.SC_OK) {
        checkServerStatus(code);
    }

    JsonElement json = new JsonParser().parse(method.getResponseBodyAsString());
    JsonArray array = json.getAsJsonArray();
    Iterator iterator = array.iterator();
    List<Task> tasks = new ArrayList<Task>();
    while (iterator.hasNext()) {
        JsonObject element = (JsonObject) iterator.next();
        IceScrumTask task = new IceScrumTask(element, this.serverUrl, this.pkey);
        tasks.add(task);
    }
    return tasks.toArray(new Task[] {});
}

From source file:com.keydap.sparrow.SparrowClient.java

License:Apache License

private <T> SearchResponse<T> sendSearchRequest(HttpUriRequest req, Class<T> resClas) {
    SearchResponse<T> result = new SearchResponse<T>();
    try {/*from ww  w .  j ava 2 s . c  o m*/
        LOG.debug("Sending {} request to {}", req.getMethod(), req.getURI());
        authenticator.addHeaders(req);
        HttpResponse resp = client.execute(req);
        authenticator.saveHeaders(resp);
        StatusLine sl = resp.getStatusLine();
        int code = sl.getStatusCode();

        LOG.debug("Received status code {} from the request to {}", code, req.getURI());

        HttpEntity entity = resp.getEntity();
        String json = null;
        if (entity != null) {
            json = EntityUtils.toString(entity);
        }

        result.setHttpBody(json);
        result.setHttpCode(code);
        result.setHeaders(resp.getAllHeaders());

        // if it is success there will be response body to read
        if (code == 200) {
            if (json != null) { // DELETE will have no response body, so check for null

                JsonObject obj = (JsonObject) new JsonParser().parse(json);
                JsonElement je = obj.get("totalResults");
                if (je != null) {
                    result.setTotalResults(je.getAsInt());
                }

                je = obj.get("startIndex");
                if (je != null) {
                    result.setStartIndex(je.getAsInt());
                }

                je = obj.get("itemsPerPage");
                if (je != null) {
                    result.setItemsPerPage(je.getAsInt());
                }

                je = obj.get("Resources"); // yes, the 'R' in resources must be upper case
                if (je != null) {
                    JsonArray arr = je.getAsJsonArray();
                    Iterator<JsonElement> itr = arr.iterator();
                    List<T> resources = new ArrayList<T>();
                    while (itr.hasNext()) {
                        JsonObject r = (JsonObject) itr.next();
                        if (resClas != null) {
                            resources.add(unmarshal(r, resClas));
                        } else {
                            T rsObj = unmarshal(r);
                            if (rsObj == null) {
                                LOG.warn(
                                        "No resgistered resource class found to deserialize the resource data {}",
                                        r);
                            } else {
                                resources.add(rsObj);
                            }
                        }
                    }

                    if (!resources.isEmpty()) {
                        result.setResources(resources);
                    }
                }
            }
        } else {
            if (json != null) {
                Error error = serializer.fromJson(json, Error.class);
                result.setError(error);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        LOG.warn("", e);
        result.setHttpCode(-1);
        Error err = new Error();

        err.setDetail(e.getMessage());
        result.setError(err);
    }
    return result;
}

From source file:com.keydap.sparrow.SparrowClient.java

License:Apache License

private JsonObject keysToLower(JsonObject obj) {
    JsonObject tmp = new JsonObject();
    for (String key : obj.keySet()) {
        JsonElement je = obj.get(key);
        if (key.contains(":")) {
            JsonObject ext = keysToLower((JsonObject) je);
            tmp.add(key, ext);/*w  ww .  j  a v  a 2 s .c o m*/
        } else {
            if (je.isJsonObject()) {
                je = keysToLower((JsonObject) je);
            } else if (je.isJsonArray()) {
                JsonArray arr = je.getAsJsonArray();
                for (int i = 0; i < arr.size(); i++) {
                    JsonElement item = arr.get(i);
                    if (item.isJsonObject()) {
                        item = keysToLower((JsonObject) item);
                        arr.set(i, item);
                    }
                }
            }

            tmp.add(key.toLowerCase(), je);
        }
    }

    return tmp;
}

From source file:com.kotcrab.vis.editor.serializer.json.ArrayJsonSerializer.java

License:Apache License

@Override
public Array<T> deserialize(JsonElement element, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    JsonArray jsonArray = element.getAsJsonArray();
    Array<T> array = new Array<>(jsonArray.size());

    for (JsonElement jsonElement : jsonArray) {
        if (jsonElement.isJsonObject()) {
            JsonObject jsonObjectElement = jsonElement.getAsJsonObject();
            if (jsonObjectElement.has(PRIMITIVE_CONTENT)) {
                array.add(context.deserialize(jsonObjectElement.get(PRIMITIVE_CONTENT),
                        GsonUtils.readClassProperty(jsonObjectElement, context)));
            } else {
                array.add(context.deserialize(jsonObjectElement,
                        GsonUtils.readClassProperty(jsonObjectElement, context)));
            }//  ww  w. j  ava2s  . c o  m

            continue;
        }

        throw new UnsupportedOperationException("Invalid JsonElement type in ArrayJsonSerializer");
    }

    return array;
}