Example usage for com.google.gson JsonArray iterator

List of usage examples for com.google.gson JsonArray iterator

Introduction

In this page you can find the example usage for com.google.gson JsonArray iterator.

Prototype

public Iterator<JsonElement> iterator() 

Source Link

Document

Returns an iterator to navigate the elements of the array.

Usage

From source file:com.ibm.streamsx.topology.internal.gson.GsonUtilities.java

License:Open Source License

public static void gclear(JsonArray array) {
    Iterator<JsonElement> it = array.iterator();
    while (it.hasNext())
        it.remove();/* w ww  . j a va 2  s  .  c  om*/
}

From source file:com.ibm.watson.movieapp.dialog.fvt.rest.RestAPI.java

License:Open Source License

/**
 * getJSONArray - read JSON and find the values associated with the element param
 * @param jsonBody = JSON to read in string form
 * @param element - element looking for//w  w  w  .  jav a  2s  . com
 * @return - String value of element
 */
public ArrayList<String> getJSONArrayValue(String jsonBody, String field) {

    ArrayList<String> values = new ArrayList<String>();

    try {
        JsonElement je = new JsonParser().parse(jsonBody);
        JsonArray inner = je.getAsJsonObject().getAsJsonArray(field);

        Iterator<JsonElement> innerIter = inner.iterator();
        while (innerIter.hasNext()) {
            JsonElement innerEntry = innerIter.next();
            values.add(innerEntry.getAsString());
        }

    } catch (JsonIOException | JsonSyntaxException e) {

        e.printStackTrace();
    }

    return values;

}

From source file:com.ibm.watson.movieapp.dialog.fvt.rest.RestAPI.java

License:Open Source License

/**
 * /*from  ww  w.  j a v  a2s .c  o m*/
 * @param type
 * @param jsonFile
 * @return
 */
public ArrayList<String> getMovieOptions(String type, String jsonFile) {

    ArrayList<String> values = new ArrayList<String>();

    try {
        if (!jsonFile.startsWith("/")) {
            jsonFile = "/" + jsonFile;
        }
        jsonFile = "/questions" + jsonFile;
        JsonElement jelmnt = new JsonParser()
                .parse(new InputStreamReader(this.getClass().getResourceAsStream(jsonFile)));
        JsonArray jarray = jelmnt.getAsJsonObject().getAsJsonArray(type);

        Iterator<JsonElement> questOpt = jarray.iterator();
        while (questOpt.hasNext()) {
            values.add(questOpt.next().getAsString());
        }

    } catch (JsonIOException | JsonSyntaxException e) {
        e.printStackTrace();
    }

    return values;

}

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);/*from  ww w  .  j  ava2 s.co 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 {/*w w  w .  jav a  2 s.  c  om*/
        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 <T> T unmarshal(JsonObject json) throws Exception {
    JsonArray schemas = json.get("schemas").getAsJsonArray();
    Iterator<JsonElement> itr = schemas.iterator();

    T obj = null;//www.  j a  v  a  2  s.  c o m

    while (itr.hasNext()) {
        String id = itr.next().getAsString();
        Class<?> rc = schemaIdClassMap.get(id);
        if (rc != null) {
            obj = (T) unmarshal(json, rc);
            break;
        }
    }

    return obj;
}

From source file:com.mifos.utils.DataTableUIBuilder.java

public LinearLayout getDataTableLayout(final DataTable dataTable, JsonArray jsonElements,
        LinearLayout parentLayout, final Context context, final int entityId,
        DataTableActionListener mListener) {
    dataTableActionListener = mListener;

    /**/*from ww  w . j a v a 2 s.  co  m*/
     * Create a Iterator with Json Elements to Iterate over the DataTable
     * Response.
     */
    Iterator<JsonElement> jsonElementIterator = jsonElements.iterator();
    /*
     * Each Row of the Data Table is Treated as a Table Here.
     * Creating the First Table for First Row
     */
    tableIndex = 0;
    while (jsonElementIterator.hasNext()) {
        TableLayout tableLayout = new TableLayout(context);
        tableLayout.setPadding(10, 10, 10, 10);

        final JsonElement jsonElement = jsonElementIterator.next();
        /*
        * Each Entry in a Data Table is Displayed in the
        * form of a table where each row contains one Key-Value Pair
        * i.e a Column Name - Column Value from the DataTable
        */
        int rowIndex = 0;
        while (rowIndex < dataTable.getColumnHeaderData().size()) {
            TableRow tableRow = new TableRow(context);
            tableRow.setLayoutParams(new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
            tableRow.setPadding(10, 10, 10, 10);
            if (rowIndex % 2 == 0) {
                tableRow.setBackgroundColor(Color.LTGRAY);
            } else {
                tableRow.setBackgroundColor(Color.WHITE);
            }

            TextView key = new TextView(context);
            key.setText(dataTable.getColumnHeaderData().get(rowIndex).getColumnName());
            key.setGravity(Gravity.LEFT);
            TextView value = new TextView(context);
            value.setGravity(Gravity.RIGHT);
            if (jsonElement.getAsJsonObject().get(dataTable.getColumnHeaderData().get(rowIndex).getColumnName())
                    .toString().contains("\"")) {
                value.setText(jsonElement.getAsJsonObject()
                        .get(dataTable.getColumnHeaderData().get(rowIndex).getColumnName()).toString()
                        .replace("\"", ""));
            } else {
                value.setText(jsonElement.getAsJsonObject()
                        .get(dataTable.getColumnHeaderData().get(rowIndex).getColumnName()).toString());
            }

            tableRow.addView(key, new TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
            tableRow.addView(value, new TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT, 1f));
            TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParams.setMargins(12, 16, 12, 16);
            tableLayout.addView(tableRow, layoutParams);

            rowIndex++;
        }

        tableLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(context, "Update Row " + tableIndex, Toast.LENGTH_SHORT).show();
            }
        });

        tableLayout.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                Toast.makeText(context, "Deleting Row " + tableIndex, Toast.LENGTH_SHORT).show();

                BaseApiManager baseApiManager = new BaseApiManager();
                DataManager dataManager = new DataManager(baseApiManager);
                Observable<GenericResponse> call = dataManager
                        .removeDataTableEntry(dataTable.getRegisteredTableName(), entityId,
                                Integer.parseInt(jsonElement.getAsJsonObject()
                                        .get(dataTable.getColumnHeaderData().get(0).getColumnName())
                                        .toString()));
                Subscription subscription = call.subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<GenericResponse>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(GenericResponse genericResponse) {
                                Toast.makeText(context, "Deleted Row " + tableIndex, Toast.LENGTH_SHORT).show();
                                dataTableActionListener.onRowDeleted();
                            }
                        });

                return true;
            }
        });

        View v = new View(context);
        v.setBackgroundColor(ContextCompat.getColor(context, R.color.black));
        parentLayout.addView(tableLayout);
        parentLayout.addView(v, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 5));
        Log.i("TABLE INDEX", "" + tableIndex);
        tableIndex++;
    }
    return parentLayout;
}

From source file:com.mycompany.mavenfirst.webManager.java

public void gsontoJsonArray() {
    String str = "[{\"name\":\"Tom\",\"city\":\"Houston\",\"country\":\"USA\"},\n"
            + "{\"name\":\"Ady\",\"city\":\"Melbourne\",\"country\":\"Australia\"}]";
    JsonElement json = new JsonParser().parse(str);
    JsonArray array = json.getAsJsonArray();
    Iterator iterator = array.iterator();
    List<Demographics> p = new ArrayList<>();
    while (iterator.hasNext()) {
        JsonObject json2 = (JsonObject) iterator.next();
        Gson gson = new Gson();
        Demographics v = gson.fromJson(json2, Demographics.class);
        p.add(v);//w w  w .  j a  v a 2  s  .c  o m
    }
    JOptionPane.showMessageDialog(null, p);
    System.out.println(p);
}

From source file:com.pearson.pdn.learningstudio.content.ContentService.java

License:Apache License

/**
 * Get content for a specific item in a course with
 * getItem(courseId, itemId)//www.ja v  a2s . c o m
 * by following the links to the item itself
 * and next to the contentUrl
 * using OAuth1 or OAuth2 as a student, teacher, or teaching assistant
 * 
 * @param courseId   ID of the course
 * @param itemId   ID of the item
 * @return   Response object with details of status and content
 * @throws IOException
 */
public Response getItemContent(String courseId, String itemId) throws IOException {
    Response response = getItem(courseId, itemId);
    if (response.isError()) {
        return response;
    }

    // should only be one item here, but it is returned in an array for some reason
    String courseItemsJson = response.getContent();
    JsonObject json = this.jsonParser.parse(courseItemsJson).getAsJsonObject();
    JsonArray items = json.get("items").getAsJsonArray();

    // again, only one element expected here...
    Iterator<JsonElement> itemIterator = items.iterator();
    if (itemIterator.hasNext()) {
        JsonObject item = itemIterator.next().getAsJsonObject();
        JsonArray links = item.get("links").getAsJsonArray();

        for (Iterator<JsonElement> linkIter = links.iterator(); linkIter.hasNext();) {
            JsonObject link = linkIter.next().getAsJsonObject();

            JsonElement title = link.get("title");
            // rel on link varies, so identify self by missing title
            if (title == null) {
                String relativeUrl = this.getRelativePath(link.get("href").getAsString());
                response = doMethod(HttpMethod.GET, relativeUrl, NO_CONTENT);
                if (response.isError()) {
                    return response;
                }

                json = this.jsonParser.parse(response.getContent()).getAsJsonObject();
                String itemType = json.entrySet().iterator().next().getKey();
                json = json.get(itemType).getAsJsonArray().get(0).getAsJsonObject(); // single element wrapped in an array
                String contentUrl = json.get("contentUrl").getAsString();
                relativeUrl = this.getRelativePath(contentUrl);

                return doMethod(HttpMethod.GET, relativeUrl, NO_CONTENT);
            }
        }
    }

    // should never get here
    throw new RuntimeException("No item content path found");
}

From source file:com.pearson.pdn.learningstudio.content.ContentService.java

License:Apache License

/**
 * Get links details from a specific item for a course with
 * Get /courses/{courseId}/items/{itemId}
 * using OAuth2 as a student, teacher or teaching assistant
 * // w ww. j  a  v  a 2 s.c om
 * Example JSON structure: (Multimedia item)
 * 
 * { 
 *   "details": { 
 *     "access": {...}, 
 *     "schedule": {...}, 
 *     "self": {...},
 *     "selfType": "textMultimedias"
 *   }
 * }
 * 
 * @param courseId   ID of the course
 * @param itemId   ID of the item
 * @return   Response object with details of status and content
 * @throws IOException
 */
public Response getItemLinkDetails(String courseId, String itemId) throws IOException {
    Response response = getItem(courseId, itemId);
    if (response.isError()) {
        return response;
    }

    // should only be one item here, but it is returned in an array for some reason
    String courseItemsJson = response.getContent();
    JsonObject json = this.jsonParser.parse(courseItemsJson).getAsJsonObject();
    JsonArray items = json.get("items").getAsJsonArray();
    JsonObject detail = new JsonObject();

    // again, only one element expected here...
    Iterator<JsonElement> itemIterator = items.iterator();
    if (itemIterator.hasNext()) {
        JsonObject item = itemIterator.next().getAsJsonObject();
        JsonArray links = item.get("links").getAsJsonArray();

        for (Iterator<JsonElement> linkIter = links.iterator(); linkIter.hasNext();) {
            JsonObject link = linkIter.next().getAsJsonObject();
            String relativeUrl = this.getRelativePath(link.get("href").getAsString());

            response = doMethod(HttpMethod.GET, relativeUrl, NO_CONTENT);
            if (response.isError()) {
                return response;
            }

            JsonElement linkElement = this.jsonParser.parse(response.getContent());

            JsonElement title = link.get("title");
            // rel on link varies, so identify self by missing title
            if (title == null) {
                Map.Entry<String, JsonElement> self = linkElement.getAsJsonObject().entrySet().iterator()
                        .next();

                linkElement = self.getValue();
                // content items like to return a single resource in an array sometimes
                if (linkElement.isJsonArray()) {
                    linkElement = linkElement.getAsJsonArray().get(0);
                }

                detail.add("self", linkElement);
                detail.addProperty("selfType", self.getKey());
            } else {
                // remove the first layer wrapper. it's just repetitive
                linkElement = linkElement.getAsJsonObject().get(title.getAsString());
                detail.add(title.getAsString(), linkElement);
            }
        }

        JsonObject detailWrapper = new JsonObject();
        detailWrapper.add("details", detail);

        response.setContent(this.gson.toJson(detailWrapper));
    } else {
        // this should never happen, but it should be detected if it does
        throw new RuntimeException("Unexpected condition in library: No items");
    }

    return response;
}