Example usage for org.json JSONArray length

List of usage examples for org.json JSONArray length

Introduction

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

Prototype

public int length() 

Source Link

Document

Get the number of elements in the JSONArray, included nulls.

Usage

From source file:com.df.app.carsWaiting.CarsWaitingListActivity.java

/**
 * //  ww  w .ja  v a2  s.c o  m
 * @param result
 */
private void fillInData(String result) {
    try {
        JSONArray jsonArray = new JSONArray(result);

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            CarsWaitingItem item = new CarsWaitingItem();
            item.setPlateNumber(jsonObject.getString("plateNumber"));
            item.setExteriorColor(jsonObject.getString("exteriorColor"));
            item.setCarType(jsonObject.getString("licenseModel"));
            item.setDate(jsonObject.getString("createDate"));
            item.setCarId(jsonObject.getInt("carId"));
            item.setJsonObject(jsonObject);

            data.add(item);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    adapter.notifyDataSetChanged();

    startNumber = data.size() + 1;

    if (data.size() == 0) {
        footerView.setVisibility(View.GONE);
    } else {
        footerView.setVisibility(View.VISIBLE);
    }

    //        for(int i = 0; i < data.size(); i++)
    //            swipeListView.closeAnimate(i);

    //        // 0, ??(?
    //        if(data.size() == 0) {
    //            DeleteFiles.deleteFiles(AppCommon.photoDirectory);
    //            DeleteFiles.deleteFiles(AppCommon.savedDirectory);
    //        }
}

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

/**
 * Make remote request to get all loyalty cards stored in Cozy
 *///from  ww  w.ja  v  a2s  .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  w  ww .  jav  a 2s .  c om*/
                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"));
    }/*w  w w.  j  ava 2s  .  c om*/
}

From source file:com.jennifer.ui.util.scale.LinearScale.java

public double get(double x) {
    int index = -1;
    int target;/*from   w w w. j  ava2  s.c  o  m*/

    JSONArray domain = domain();

    for (int i = 0, len = domain.length(); i < len; i++) {

        if (i == len - 1) {
            if (x == domain.getDouble(i)) {
                index = i;
                break;
            }
        } else {
            if (domain.getDouble(i) < domain.getDouble(i + 1)) {
                if (x >= domain.getDouble(i) && x < domain.getDouble(i + 1)) {
                    index = i;
                    break;
                }
            } else if (domain.getDouble(i) >= domain.getDouble(i + 1)) {
                if (x <= domain.getDouble(i) && domain.getDouble(i + 1) < x) {
                    index = i;
                    break;
                }
            }
        }
    }

    JSONArray range = range();

    if (range.length() == 0) {
        if (index == 0) {
            return 0;
        } else if (index == -1) {
            return 1;
        } else {
            double min = domain.getDouble(index - 1);
            double max = domain.getDouble(index);

            double pos = (x - min) / (max - min);

            return pos;
        }
    } else {

        if (domain.length() - 1 == index) {
            return range.getDouble(index);
        } else if (index == -1) {

            double max = max();
            double min = min();

            if (max < x) {

                if (_clamp)
                    return max;

                double last = domain.getDouble(domain.length() - 1);
                double last2 = domain.getDouble(domain.length() - 2);

                double rlast = range.getDouble(range.length() - 1);
                double rlast2 = range.getDouble(range.length() - 2);

                double distLast = Math.abs(last - last2);
                double distRLast = Math.abs(rlast - rlast2);

                return rlast + Math.abs(x - max) * distRLast / distLast;

            } else if (min > x) {

                if (_clamp)
                    return min;

                double first = domain.getDouble(0);
                double first2 = domain.getDouble(1);

                double rfirst = range.getDouble(0);
                double rfirst2 = range.getDouble(1);

                double distFirst = Math.abs(first - first2);
                double distRFirst = Math.abs(rfirst - rfirst2);

                return rfirst - Math.abs(x - min) * distRFirst / distFirst;
            }

            return range.getDouble(range.length() - 1);
        } else {

            double min = domain.getDouble(index);
            double max = domain.getDouble(index + 1);

            double minR = range.getDouble(index);
            double maxR = range.getDouble(index + 1);

            double pos = (x - min) / (max - min);

            double scale = _round ? MathUtil.interpolateRound(minR, maxR, pos)
                    : MathUtil.interpolateNumber(minR, maxR, pos);

            return scale;

        }
    }

}

From source file:com.jennifer.ui.util.scale.LinearScale.java

public JSONArray ticks(int count, boolean isNice, int intNumber) {
    JSONArray list = new JSONArray();

    JSONArray domain = domain();/*from w w w . ja  va 2 s  .c  om*/

    if (domain.getDouble(0) == 0 && domain.getDouble(1) == 0) {
        return new JSONArray();
    }

    JSONArray arr = MathUtil.nice(domain.getDouble(0), domain.getDouble(1), count, isNice);

    double min = arr.getDouble(0);
    double max = arr.getDouble(1);
    double range = arr.getDouble(2);
    double spacing = arr.getDouble(3);

    double start = min * intNumber;
    double end = max * intNumber;
    while (start <= end) {
        list.put(start / intNumber);
        start += spacing * intNumber;
    }

    if (list.getDouble(list.length() - 1) * intNumber != end && start > end) {
        list.put(end / intNumber);
    }

    return list;
}

From source file:com.muzima.service.PreferenceService.java

protected List<String> deserialize(String json) {
    if (StringUtils.isEmpty(json))
        return new ArrayList<String>();

    List<String> cohortsList = new ArrayList<String>();
    try {//w  w  w  .ja va 2 s .c o  m
        JSONArray jsonArray = new JSONArray(json);
        for (int i = 0; i < jsonArray.length(); i++) {
            cohortsList.add(jsonArray.get(i).toString());
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return cohortsList;
}

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

/**
 * Parses the specified method call for an article.
 * /* www  .j a  va 2  s  .co  m*/
 * @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  ww  w. j  av  a  2  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}/*from www  . j  av  a 2s.com*/
 * @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;
}