Example usage for org.json JSONArray getJSONObject

List of usage examples for org.json JSONArray getJSONObject

Introduction

In this page you can find the example usage for org.json JSONArray getJSONObject.

Prototype

public JSONObject getJSONObject(int index) throws JSONException 

Source Link

Document

Get the JSONObject associated with an index.

Usage

From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java

/**
 * Make remote request to get all loyalty cards stored in Cozy
 *//*from  w w  w. j a  v a  2  s  .c om*/
public String getRemoteExpenses() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new ExpenseSyncEvent(SYNC_MESSAGE, "Your Cozy has no expenses stored."));
                Expense.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        EventBus.getDefault().post(new ExpenseSyncEvent(SYNC_MESSAGE,
                                "Reading expenses on Cozy " + i + "/" + jsonArray.length() + "..."));
                        JSONObject expenseJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        Expense expense = Expense.getByRemoteId(expenseJson.get("_id").toString());
                        if (expense == null) {
                            expense = new Expense(expenseJson);
                        } else {
                            expense.setRemoteId(expenseJson.getString("_id"));
                            expense.setAmount(expenseJson.getDouble("amount"));
                            expense.setCategory(expenseJson.getString("category"));
                            expense.setDate(expenseJson.getString("date"));

                            if (expenseJson.has("deviceId")) {
                                expense.setDeviceId(expenseJson.getString("deviceId"));
                            } else {
                                expense.setDeviceId(Device.registeredDevice().getLogin());
                            }
                        }
                        expense.save();

                        if (expenseJson.has("receipts")) {
                            JSONArray receiptsArray = expenseJson.getJSONArray("receipts");

                            for (int j = 0; j < receiptsArray.length(); j++) {
                                JSONObject recJsonObject = receiptsArray.getJSONObject(i);
                                Receipt receipt = new Receipt();
                                receipt.setBase64(recJsonObject.getString("base64"));
                                receipt.setExpense(expense);
                                receipt.setName("");
                                receipt.save();
                            }
                        }
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

From source file:com.axinom.drm.quickstart.activity.SampleChooserActivity.java

private void makeMoviesRequest() {
    JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, API_CATALOG, null,
            new Response.Listener<JSONArray>() {
                @Override/*from   ww  w.ja v  a 2 s  .  c o m*/
                public void onResponse(JSONArray response) {
                    // Adding video URLs and names to lists from json array response.
                    for (int i = 0; i < response.length(); i++) {
                        try {
                            JSONObject jsonObject = response.getJSONObject(i);
                            mVideoUrls.add(jsonObject.getString("url"));
                            mVideoNames.add(jsonObject.getString("name"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    ArrayAdapter adapter = new ArrayAdapter<String>(getApplicationContext(),
                            android.R.layout.simple_list_item_1, mVideoNames) {
                        @Override
                        public View getView(int position, View convertView, ViewGroup parent) {
                            View view = super.getView(position, convertView, parent);
                            TextView textView = (TextView) view.findViewById(android.R.id.text1);
                            textView.setTextColor(Color.BLACK);
                            return view;
                        }
                    };
                    mListView.setAdapter(adapter);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d(TAG, "Movies json was not loaded with error: " + error.getMessage());
                }
            });
    BaseApp.requestQueue.add(request);
}

From source file:jGW2API.util.event.EventNames.java

public EventNames(JSONArray json) {
    this.eventNames = new HashMap();
    for (int i = 0; i < json.length(); i++) {
        this.eventNames.put(json.getJSONObject(i).getString("id"), json.getJSONObject(i).getString("name"));
    }/*from  www .ja  v a2s  .c  o m*/
}

From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java

/**
 * MetaWeblog requests processing.//from ww w.  j a v  a2 s.  c  o m
 * 
 * @param request the specified http servlet request
 * @param response the specified http servlet response
 * @param context the specified http request context
 */
@RequestProcessing(value = "/apis/metaweblog", method = HTTPRequestMethod.POST)
public void metaWeblog(final HttpServletRequest request, final HttpServletResponse response,
        final HTTPRequestContext context) {
    final TextXMLRenderer renderer = new TextXMLRenderer();
    context.setRenderer(renderer);

    String responseContent = null;
    try {
        final ServletInputStream inputStream = request.getInputStream();
        final String xml = IOUtils.toString(inputStream, "UTF-8");
        final JSONObject requestJSONObject = XML.toJSONObject(xml);

        final JSONObject methodCall = requestJSONObject.getJSONObject(METHOD_CALL);
        final String methodName = methodCall.getString(METHOD_NAME);
        LOGGER.log(Level.INFO, "MetaWeblog[methodName={0}]", methodName);

        final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param");

        if (METHOD_DELETE_POST.equals(methodName)) {
            params.remove(0); // Removes the first argument "appkey"
        }

        final String userEmail = params.getJSONObject(INDEX_USER_EMAIL).getJSONObject("value")
                .getString("string");
        final JSONObject user = userQueryService.getUserByEmail(userEmail);
        if (null == user) {
            throw new Exception("No user[email=" + userEmail + "]");
        }

        final String userPwd = params.getJSONObject(INDEX_USER_PWD).getJSONObject("value").getString("string");
        if (!user.getString(User.USER_PASSWORD).equals(userPwd)) {
            throw new Exception("Wrong password");
        }

        if (METHOD_GET_USERS_BLOGS.equals(methodName)) {
            responseContent = getUsersBlogs();
        } else if (METHOD_GET_CATEGORIES.equals(methodName)) {
            responseContent = getCategories();
        } else if (METHOD_GET_RECENT_POSTS.equals(methodName)) {
            final int numOfPosts = params.getJSONObject(INDEX_NUM_OF_POSTS).getJSONObject("value")
                    .getInt("int");
            responseContent = getRecentPosts(numOfPosts);
        } else if (METHOD_NEW_POST.equals(methodName)) {
            final JSONObject article = parsetPost(methodCall);
            article.put(Article.ARTICLE_AUTHOR_EMAIL, userEmail);
            addArticle(article);

            final StringBuilder stringBuilder = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><params><param><value><string>")
                            .append(article.getString(Keys.OBJECT_ID))
                            .append("</string></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else if (METHOD_GET_POST.equals(methodName)) {
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value")
                    .getString("string");
            responseContent = getPost(postId);
        } else if (METHOD_EDIT_POST.equals(methodName)) {
            final JSONObject article = parsetPost(methodCall);
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value")
                    .getString("string");
            article.put(Keys.OBJECT_ID, postId);

            article.put(Article.ARTICLE_AUTHOR_EMAIL, userEmail);
            final JSONObject updateArticleRequest = new JSONObject();
            updateArticleRequest.put(Article.ARTICLE, article);
            articleMgmtService.updateArticle(updateArticleRequest);

            final StringBuilder stringBuilder = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><params><param><value><string>")
                            .append(postId).append("</string></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else if (METHOD_DELETE_POST.equals(methodName)) {
            final String postId = params.getJSONObject(INDEX_POST_ID).getJSONObject("value")
                    .getString("string");
            articleMgmtService.removeArticle(postId);

            final StringBuilder stringBuilder = new StringBuilder(
                    "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><params><param><value><boolean>")
                            .append(true).append("</boolean></value></param></params></methodResponse>");
            responseContent = stringBuilder.toString();
        } else {
            throw new UnsupportedOperationException("Unsupported method[name=" + methodName + "]");
        }
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);

        responseContent = "";
        final StringBuilder stringBuilder = new StringBuilder(
                "<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodResponse><fault><value><struct>")
                        .append("<member><name>faultCode</name><value><int>500</int></value></member>")
                        .append("<member><name>faultString</name><value><string>").append(e.getMessage())
                        .append("</string></value></member></struct></value></fault></methodResponse>");
        responseContent = stringBuilder.toString();
    }

    renderer.setContent(responseContent);
}

From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java

/**
 * Parses the specified method call for an article.
 * /*from www  . j  a  v  a2  s . c  om*/
 * @param methodCall the specified method call
 * @return article
 * @throws Exception exception 
 */
private JSONObject parsetPost(final JSONObject methodCall) throws Exception {
    final JSONObject ret = new JSONObject();

    final JSONArray params = methodCall.getJSONObject("params").getJSONArray("param");
    final JSONObject post = params.getJSONObject(INDEX_POST).getJSONObject("value").getJSONObject("struct");
    final JSONArray members = post.getJSONArray("member");

    for (int i = 0; i < members.length(); i++) {
        final JSONObject member = members.getJSONObject(i);
        final String name = member.getString("name");

        if ("dateCreated".equals(name)) {
            final JSONObject preference = preferenceQueryService.getPreference();

            final String dateString = member.getJSONObject("value").getString("dateTime.iso8601");
            Date date = null;
            try {
                date = (Date) DateFormatUtils.ISO_DATETIME_FORMAT.parseObject(dateString);
            } catch (final ParseException e) {
                LOGGER.log(Level.WARNING,
                        "Parses article create date failed with ISO8601, retry to parse with pattern[yyyy-MM-dd'T'HH:mm:ss]");
                final String timeZoneId = preference.getString(Preference.TIME_ZONE_ID);
                final TimeZone timeZone = TimeZone.getTimeZone(timeZoneId);
                final DateFormat format = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss");
                format.setTimeZone(timeZone);
                date = format.parse(dateString);
            }
            ret.put(Article.ARTICLE_CREATE_DATE, date);
        } else if ("title".equals(name)) {
            ret.put(Article.ARTICLE_TITLE, member.getJSONObject("value").getString("string"));
        } else if ("description".equals(name)) {
            final String content = member.getJSONObject("value").getString("string");
            ret.put(Article.ARTICLE_CONTENT, content);

            final String plainTextContent = Jsoup.parse(content).text();
            if (plainTextContent.length() > ARTICLE_ABSTRACT_LENGTH) {
                ret.put(Article.ARTICLE_ABSTRACT, plainTextContent.substring(0, ARTICLE_ABSTRACT_LENGTH));
            } else {
                ret.put(Article.ARTICLE_ABSTRACT, plainTextContent);
            }
        } else if ("categories".equals(name)) {
            final StringBuilder tagBuilder = new StringBuilder();

            final JSONObject data = member.getJSONObject("value").getJSONObject("array").getJSONObject("data");
            if (0 == data.length()) {
                throw new Exception("At least one Tag");
            }

            final Object value = data.get("value");
            if (value instanceof JSONArray) {
                final JSONArray tags = (JSONArray) value;
                for (int j = 0; j < tags.length(); j++) {
                    final String tagTitle = tags.getJSONObject(j).getString("string");
                    tagBuilder.append(tagTitle);

                    if (j < tags.length() - 1) {
                        tagBuilder.append(",");
                    }
                }
            } else {
                final JSONObject tag = (JSONObject) value;
                tagBuilder.append(tag.getString("string"));
            }

            ret.put(Article.ARTICLE_TAGS_REF, tagBuilder.toString());
        }
    }

    final boolean publish = 1 == params.getJSONObject(INDEX_PUBLISH).getJSONObject("value").getInt("boolean")
            ? true
            : false;
    ret.put(Article.ARTICLE_IS_PUBLISHED, publish);

    ret.put(Article.ARTICLE_COMMENTABLE, true);
    ret.put(Article.ARTICLE_VIEW_PWD, "");

    return ret;
}

From source file:org.b3log.solo.api.metaweblog.MetaWeblogAPI.java

/**
 * Builds a post (post struct) with the specified post id.
 * /*from  w ww .  j ava2  s  . c  o  m*/
 * @param postId the specified post id
 * @return blog info XML
 * @throws Exception exception 
 */
private String buildPost(final String postId) throws Exception {
    final StringBuilder stringBuilder = new StringBuilder();

    final JSONObject result = articleQueryService.getArticle(postId);

    if (null == result) {
        throw new Exception("Not found article[id=" + postId + "]");
    }

    final JSONObject article = result.getJSONObject(Article.ARTICLE);

    final Date createDate = (Date) article.get(Article.ARTICLE_CREATE_DATE);
    final String articleTitle = StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_TITLE));

    stringBuilder.append("<struct>");

    stringBuilder.append("<member><name>dateCreated</name>").append("<value><dateTime.iso8601>")
            .append(DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT.format(createDate))
            .append("</dateTime.iso8601></value></member>");

    stringBuilder.append("<member><name>description</name>").append("<value>")
            .append(StringEscapeUtils.escapeXml(article.getString(Article.ARTICLE_CONTENT)))
            .append("</value></member>");

    stringBuilder.append("<member><name>title</name>").append("<value>").append(articleTitle)
            .append("</value></member>");

    stringBuilder.append("<member><name>categories</name>").append("<value><array><data>");
    final JSONArray tags = article.getJSONArray(Article.ARTICLE_TAGS_REF);
    for (int i = 0; i < tags.length(); i++) {
        final String tagTitle = tags.getJSONObject(i).getString(Tag.TAG_TITLE);
        stringBuilder.append("<value>").append(tagTitle).append("</value>");
    }
    stringBuilder.append("</data></array></value></member></struct>");

    return stringBuilder.toString();
}

From source file:com.inductiveautomation.reporting.examples.datasource.common.RestJsonDataSource.java

/**
 * Looks through the {@link JSONArray}, evaluating each {@link JSONObject} to determine which has the largest
 * set of keys.  This process is useful because not all JSON objects in an array may have the same key set.  There
 * are some assumptions made that the largest keyset will contain all the keys available in those of lower sets.
 * This is far from true, but this assumption is allowed for the sake of simplicity for this example.
 * @param jsonArray a {@link JSONArray}/* w w  w. j a va  2  s.  c  om*/
 * @return a JSONObject containing the most keys found in the array.  May be empty.
 */
private JSONObject findReferenceObjectIndex(JSONArray jsonArray) throws JSONException {
    JSONObject reference = null;
    if (jsonArray != null && jsonArray.length() > 0) {
        reference = jsonArray.getJSONObject(0);

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jo = jsonArray.getJSONObject(i);
            if (Iterators.size(jo.keys()) > Iterators.size(reference.keys())) {
                reference = jo;
            }
        }
    }
    return reference == null ? new JSONObject() : reference;
}

From source file:com.inductiveautomation.reporting.examples.datasource.common.RestJsonDataSource.java

/**
 * Creates and returns {@link Dataset} with String column types from a {@link JSONArray}.  Returns empty if no data
 * was found and an exception was not thrown.
 *//*from  w  w w.j  a  v  a 2 s. c o  m*/
private Dataset createDatasetFromJSONArray(JSONArray jsonArray) throws JSONException {
    Dataset ds = null;

    if (jsonArray.length() >= 1) {
        // JSON objects in an array may not have values for each key, so make sure we
        // get the full keyset
        JSONObject reference = findReferenceObjectIndex(jsonArray);

        // get column names from the reference object
        List<String> colNames = new ArrayList<>();
        Iterator keys = reference.keys();
        while (keys.hasNext()) {
            colNames.add(keys.next().toString());
        }

        // now start building dataset to pass into report engine
        DatasetBuilder builder = new DatasetBuilder();
        builder.colNames(colNames.toArray(new String[colNames.size()]));

        // set the column types. We're using all strings in this example, but we could be
        // checking for numeric types and setting different column types to enable calculations
        Class[] types = new Class[colNames.size()];
        for (int i = 0; i < types.length; i++) {
            types[i] = String.class;
        }
        builder.colTypes(types);

        // now create rows for each json list value
        for (int row = 0; row < jsonArray.length(); row++) {
            String[] rowData = new String[colNames.size()];
            for (int col = 0; col < colNames.size(); col++) {
                try {
                    rowData[col] = jsonArray.getJSONObject(row).get(colNames.get(col)).toString();
                } catch (JSONException e) {
                    // ignore because it just means this object didn't have our key
                }
            }
            builder.addRow(rowData);
        }
        ds = builder.build();
    }
    return ds != null ? ds : new BasicDataset();
}

From source file:org.aosutils.android.youtube.YtApiClientV3.java

private static SearchResultIds searchYtIds(String query, String type, int maxResults, String pageToken,
        String apiKey) throws IOException, JSONException {
    ArrayList<String> ids = new ArrayList<>();

    Builder uriBuilder = new Uri.Builder().scheme("https").authority("www.googleapis.com")
            .path("/youtube/v3/search").appendQueryParameter("key", apiKey).appendQueryParameter("part", "id")
            .appendQueryParameter("order", "relevance")
            .appendQueryParameter("maxResults", Integer.toString(maxResults)).appendQueryParameter("q", query);

    if (type != null) {
        uriBuilder.appendQueryParameter("type", type);
    }/* ww  w  .jav  a 2 s.com*/
    if (pageToken != null) {
        uriBuilder.appendQueryParameter("pageToken", pageToken);
    }

    String uri = uriBuilder.build().toString();
    String output = HttpUtils.get(uri, null, _YtApiConstants.HTTP_TIMEOUT);

    JSONObject jsonObject = new JSONObject(output);

    String nextPageToken = jsonObject.has("nextPageToken") ? jsonObject.getString("nextPageToken") : null;
    JSONArray items = jsonObject.getJSONArray("items");

    for (int i = 0; i < items.length(); i++) {
        JSONObject item = items.getJSONObject(i);
        JSONObject id = item.getJSONObject("id");

        ids.add(id.has("videoId") ? id.getString("videoId") : id.getString("playlistId"));
    }

    SearchResultIds searchResult = new SearchResultIds(ids, nextPageToken);

    return searchResult;
}

From source file:org.aosutils.android.youtube.YtApiClientV3.java

private static SearchResultIds playlistVideoIds(String playlistId, int maxResults, String pageToken,
        String apiKey) throws IOException, JSONException {
    ArrayList<String> ids = new ArrayList<>();

    Builder uriBuilder = new Uri.Builder().scheme("https").authority("www.googleapis.com")
            .path("/youtube/v3/playlistItems").appendQueryParameter("key", apiKey)
            .appendQueryParameter("part", "id,snippet")
            .appendQueryParameter("maxResults", Integer.toString(maxResults))
            .appendQueryParameter("playlistId", playlistId);

    if (pageToken != null) {
        uriBuilder.appendQueryParameter("pageToken", pageToken);
    }//from  w w  w.  j a  v a 2  s.com

    String uri = uriBuilder.build().toString();
    String output = HttpUtils.get(uri, null, _YtApiConstants.HTTP_TIMEOUT);

    JSONObject jsonObject = new JSONObject(output);

    String nextPageToken = jsonObject.has("nextPageToken") ? jsonObject.getString("nextPageToken") : null;
    JSONArray items = jsonObject.getJSONArray("items");

    for (int i = 0; i < items.length(); i++) {
        JSONObject item = items.getJSONObject(i);
        JSONObject snippet = item.getJSONObject("snippet");

        JSONObject resourceId = snippet.getJSONObject("resourceId");
        ids.add(resourceId.getString("videoId"));
    }

    SearchResultIds searchResult = new SearchResultIds(ids, nextPageToken);

    return searchResult;
}