Example usage for org.json JSONArray JSONArray

List of usage examples for org.json JSONArray JSONArray

Introduction

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

Prototype

public JSONArray() 

Source Link

Document

Construct an empty JSONArray.

Usage

From source file:com.nginious.http.serialize.JsonBeanCollectionSerializer.java

/**
 * Serializes the specified collection of bean elements into a JSON array.
 * //from w  w  w . j  a  v a2s. c om
 * @param items the given collection of beans to serialize
 * @return the serialized JSON array
 * @throws SerializerException if unable to serialize collection
 */
public JSONArray serialize(Collection<E> items) throws SerializerException {
    if (items == null) {
        return null;
    }

    JSONArray array = new JSONArray();

    for (E item : items) {
        JSONObject object = elementSerializer.serialize(item);
        array.put(object);
    }

    return array;
}

From source file:feedme.controller.UpdateCategoryServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from   ww  w.  ja va  2 s .c om*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    String city = request.getParameter("city");
    HashMap<String, Integer> cat = new DbHPOnLoad().getCategoriesByCity(city);
    try {

        JSONObject catObj = new JSONObject();
        catObj.put("categorys", new JSONArray());
        JSONArray cate = catObj.getJSONArray("categorys");
        for (Map.Entry<String, Integer> entry : cat.entrySet()) {
            cate.put(new JSONObject().put("cat_id", entry.getValue()).put("cat_name", entry.getKey()));
        }
        response.setContentType("application/json");
        PrintWriter writer = response.getWriter();
        writer.print(catObj);
        response.getWriter().flush();

    } catch (JSONException ex) {
        Logger.getLogger(OrderCompleteServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.asd.littleprincesbeauty.data.SqlNote.java

public JSONObject getContent() {
    try {/*  w  w w .  j a  v  a  2  s  .  c o  m*/
        JSONObject js = new JSONObject();

        if (mIsCreate) {
            Log.e(TAG, "it seems that we haven't created this in database yet");
            return null;
        }

        JSONObject note = new JSONObject();
        if (mType == Notes.TYPE_NOTE) {
            note.put(NoteColumns.ID, mId);
            note.put(NoteColumns.ALERTED_DATE, mAlertDate);
            note.put(NoteColumns.BG_COLOR_ID, mBgColorId);
            note.put(NoteColumns.CREATED_DATE, mCreatedDate);
            note.put(NoteColumns.HAS_ATTACHMENT, mHasAttachment);
            note.put(NoteColumns.MODIFIED_DATE, mModifiedDate);
            note.put(NoteColumns.PARENT_ID, mParentId);
            note.put(NoteColumns.SNIPPET, mSnippet);
            note.put(NoteColumns.TYPE, mType);
            note.put(NoteColumns.WIDGET_ID, mWidgetId);
            note.put(NoteColumns.WIDGET_TYPE, mWidgetType);
            note.put(NoteColumns.ORIGIN_PARENT_ID, mOriginParent);
            js.put(GTaskStringUtils.META_HEAD_NOTE, note);

            JSONArray dataArray = new JSONArray();
            for (SqlData sqlData : mDataList) {
                JSONObject data = sqlData.getContent();
                if (data != null) {
                    dataArray.put(data);
                }
            }
            js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
        } else if (mType == Notes.TYPE_FOLDER || mType == Notes.TYPE_SYSTEM) {
            note.put(NoteColumns.ID, mId);
            note.put(NoteColumns.TYPE, mType);
            note.put(NoteColumns.SNIPPET, mSnippet);
            js.put(GTaskStringUtils.META_HEAD_NOTE, note);
        }

        return js;
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }
    return null;
}

From source file:reseau.jeu.serveur.Protocole.java

public static String construireMsgJoueursEtat(ArrayList<Joueur> joueurs) {
    JSONObject msg = new JSONObject();
    JSONArray JSONjoueurs = new JSONArray();

    try {//from   ww w  . j a  va  2  s.  com
        msg.put("TYPE", JOUEURS_ETAT);

        Joueur joueur;
        JSONObject JSONjoueur;

        for (int j = 0; j < joueurs.size(); j++) {
            // recuperation du joueur
            joueur = joueurs.get(j);

            // construction du joueur
            JSONjoueur = new JSONObject();
            JSONjoueur.put("ID_JOUEUR", joueur.getId());
            JSONjoueur.put("NOM_JOUEUR", joueur.getPseudo());
            JSONjoueur.put("ID_EMPLACEMENT", joueur.getEmplacement().getId());
            JSONjoueur.put("ID_EQUIPE", joueur.getEquipe().getId());

            // ajout  la liste des joueurs
            JSONjoueurs.put(JSONjoueur);
        }

        msg.put("JOUEURS", JSONjoueurs);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return msg.toString();
}

From source file:reseau.jeu.serveur.Protocole.java

public static String construireMsgPartieTerminee(Jeu jeu) {
    JSONObject msg = new JSONObject();

    try {//ww  w . j  av  a 2 s. c  om
        msg.put("TYPE", PARTIE_ETAT);
        msg.put("ETAT", PARTIE_TERMINEE);

        // construction des tats des quipes
        JSONArray JSONequipes = new JSONArray();
        for (Equipe e : jeu.getEquipes()) {
            JSONObject JSONequipe = new JSONObject();

            JSONequipe.put("ID_EQUIPE", e.getId());

            if (e.estHorsJeu())
                JSONequipe.put("NB_VIES_RESTANTES", 0);
            else
                JSONequipe.put("NB_VIES_RESTANTES", e.getNbViesRestantes());

            JSONequipes.put(JSONequipe);
        }
        msg.put("EQUIPES", JSONequipes);

        // TODO construction des tats des joueurs
        // ...
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return msg.toString();
}

From source file:com.hichinaschool.flashcards.anki.StudyOptionsFragment.java

private void onPrepareDialog(int id, StyledDialog styledDialog) {
    Resources res = getResources();
    switch (id) {
    case DIALOG_CUSTOM_STUDY_DETAILS:
        styledDialog.setTitle(res.getStringArray(R.array.custom_study_options_labels)[mCustomDialogChoice]);
        switch (mCustomDialogChoice + 1) {
        case CUSTOM_STUDY_NEW:
            if (AnkiDroidApp.colIsOpen()) {
                Collection col = AnkiDroidApp.getCol();
                mCustomStudyTextView1.setText(res.getString(R.string.custom_study_new_total_new,
                        col.getSched().totalNewForCurrentDeck()));
            }/*from w ww. ja v  a2 s. c om*/
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_new_extend));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("extendNew", 10)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (AnkiDroidApp.colIsOpen()) {
                                try {
                                    int n = Integer.parseInt(mCustomStudyEditText.getText().toString());
                                    AnkiDroidApp.getSharedPrefs(getActivity()).edit().putInt("extendNew", n)
                                            .commit();
                                    Collection col = AnkiDroidApp.getCol();
                                    JSONObject deck = col.getDecks().current();
                                    deck.put("extendNew", n);
                                    col.getDecks().save(deck);
                                    col.getSched().extendLimits(n, 0);
                                    resetAndUpdateValuesFromDeck();
                                    finishCongrats();
                                } catch (NumberFormatException e) {
                                    // ignore non numerical values
                                    Themes.showThemedToast(getActivity().getBaseContext(),
                                            getResources().getString(R.string.custom_study_invalid_number),
                                            false);
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    });
            break;

        case CUSTOM_STUDY_REV:
            if (AnkiDroidApp.colIsOpen()) {
                Collection col = AnkiDroidApp.getCol();
                mCustomStudyTextView1.setText(res.getString(R.string.custom_study_rev_total_rev,
                        col.getSched().totalRevForCurrentDeck()));
            }
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_rev_extend));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("extendRev", 10)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (AnkiDroidApp.colIsOpen()) {
                                try {
                                    int n = Integer.parseInt(mCustomStudyEditText.getText().toString());
                                    AnkiDroidApp.getSharedPrefs(getActivity()).edit().putInt("extendRev", n)
                                            .commit();
                                    Collection col = AnkiDroidApp.getCol();
                                    JSONObject deck = col.getDecks().current();
                                    deck.put("extendRev", n);
                                    col.getDecks().save(deck);
                                    col.getSched().extendLimits(0, n);
                                    resetAndUpdateValuesFromDeck();
                                    finishCongrats();
                                } catch (NumberFormatException e) {
                                    // ignore non numerical values
                                    Themes.showThemedToast(getActivity().getBaseContext(),
                                            getResources().getString(R.string.custom_study_invalid_number),
                                            false);
                                } catch (JSONException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        }
                    });
            break;

        case CUSTOM_STUDY_FORGOT:
            mCustomStudyTextView1.setText("");
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_forgotten));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("forgottenDays", 2)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            JSONArray ar = new JSONArray();
                            try {
                                int forgottenDays = Integer
                                        .parseInt(((EditText) mCustomStudyEditText).getText().toString());
                                ar.put(0, 1);
                                createFilteredDeck(ar,
                                        new Object[] { String.format(Locale.US, "rated:%d:1", forgottenDays),
                                                9999, Sched.DYN_RANDOM },
                                        false);
                            } catch (NumberFormatException e) {
                                // ignore non numerical values
                                Themes.showThemedToast(getActivity().getBaseContext(),
                                        getResources().getString(R.string.custom_study_invalid_number), false);
                            } catch (JSONException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    });
            break;

        case CUSTOM_STUDY_AHEAD:
            mCustomStudyTextView1.setText("");
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_ahead));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("aheadDays", 1)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                int days = Integer
                                        .parseInt(((EditText) mCustomStudyEditText).getText().toString());
                                createFilteredDeck(new JSONArray(), new Object[] {
                                        String.format(Locale.US, "prop:due<=%d", days), 9999, Sched.DYN_DUE },
                                        true);
                            } catch (NumberFormatException e) {
                                // ignore non numerical values
                                Themes.showThemedToast(getActivity().getBaseContext(),
                                        getResources().getString(R.string.custom_study_invalid_number), false);
                            }
                        }
                    });
            break;

        case CUSTOM_STUDY_RANDOM:
            mCustomStudyTextView1.setText("");
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_random));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("randomCards", 100)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                int randomCards = Integer
                                        .parseInt(((EditText) mCustomStudyEditText).getText().toString());
                                createFilteredDeck(new JSONArray(),
                                        new Object[] { "", randomCards, Sched.DYN_RANDOM }, true);
                            } catch (NumberFormatException e) {
                                // ignore non numerical values
                                Themes.showThemedToast(getActivity().getBaseContext(),
                                        getResources().getString(R.string.custom_study_invalid_number), false);
                            }
                        }
                    });
            break;

        case CUSTOM_STUDY_PREVIEW:
            mCustomStudyTextView1.setText("");
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_preview));
            mCustomStudyEditText.setText(
                    Integer.toString(AnkiDroidApp.getSharedPrefs(getActivity()).getInt("previewDays", 1)));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String previewDays = ((EditText) mCustomStudyEditText).getText().toString();
                            createFilteredDeck(new JSONArray(),
                                    new Object[] { "is:new added:" + previewDays, 9999, Sched.DYN_OLDEST },
                                    false);
                        }
                    });
            break;

        case CUSTOM_STUDY_TAGS:
            mCustomStudyTextView1.setText("");
            mCustomStudyTextView2.setText(res.getString(R.string.custom_study_tags));
            mCustomStudyEditText
                    .setText(AnkiDroidApp.getSharedPrefs(getActivity()).getString("customTags", ""));
            styledDialog.setButtonOnClickListener(Dialog.BUTTON_POSITIVE,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String tags = ((EditText) mCustomStudyEditText).getText().toString();
                            createFilteredDeck(new JSONArray(),
                                    new Object[] { "(is:new or is:due) " + tags, 9999, Sched.DYN_RANDOM },
                                    true);
                        }
                    });
            break;
        }
    }
}

From source file:sh.calaba.driver.server.CalabashProxy.java

public JSONArray getAllSessionDetails() {
    JSONArray sessions = new JSONArray();
    if (!sessionConnectors.isEmpty()) {
        for (Map.Entry<String, CalabashAndroidConnector> entry : sessionConnectors.entrySet()) {
            JSONObject jsonEntry = new JSONObject();
            try {
                jsonEntry.put("id", entry.getKey());
                jsonEntry.put("capabilities",
                        new JSONObject(entry.getValue().getSessionCapabilities().getRawCapabilities()));
                sessions.put(jsonEntry);
            } catch (JSONException e) {
                throw new CalabashException("Error occured while JSON handling: ", e);
            }/*from   w  w w. j  ava2 s  . c o m*/
        }
    }

    return sessions;
}

From source file:com.jennifer.ui.chart.grid.DateGrid.java

public void drawBefore() {
    initDomain();//from  ww  w  .jav a2 s  .  c om

    int max = chart.area("height");

    if (orient == Orient.TOP || orient == Orient.BOTTOM) {
        max = chart.area("width");
    }

    JSONArray range = (JSONArray) new JSONArray().put(0).put(max);

    TimeScale timeScale = (TimeScale) this.scale;

    timeScale.domain(options.getJSONArray("domain")).rangeRound(range);

    boolean realtime = options.optBoolean("realtime", false);
    JSONArray step = JSONUtil.clone(options.getJSONArray("step"));

    if (realtime) {
        this.ticks = timeScale.realTicks(step.getString(0), step.getInt(1));
    } else {
        this.ticks = timeScale.ticks(step.getString(0), step.getInt(1));
    }

    // step = [this.time.days, 1];
    this.bar = 6;

    this.values = new JSONArray();

    for (int i = 0, len = this.ticks.length(); i < len; i++) {
        this.values.put(this.scale.get(this.ticks.getDouble(i)));
    }
}

From source file:com.jennifer.ui.chart.grid.DateGrid.java

private void initDomain() {

    if (has("target") && !has("domain")) {

        if (options.get("target") instanceof String) {
            JSONArray list = new JSONArray();
            list.put(options.getString("target"));
            options.put("target", list);
        }//from   w w  w  .  j  a  v a2s.co  m

        JSONArray target = (JSONArray) options.getJSONArray("target");
        JSONArray domain = new JSONArray();
        JSONArray data = chart.data();

        long min = 0;
        long max = 0;

        boolean hasMin = options.has("min");
        boolean hasMax = options.has("max");

        for (int i = 0, len = target.length(); i < len; i++) {
            String key = target.getString(i);

            for (int index = 0, dataLength = data.length(); index < dataLength; index++) {
                JSONObject row = data.getJSONObject(index);

                long value = 0;

                if (row.get(key) instanceof Date) {
                    value = ((Date) row.get(key)).getTime();
                } else {
                    value = row.getLong(key);
                }

                if (!hasMin) {
                    min = value;
                    hasMin = true;
                } else if (min > value)
                    min = value;

                if (!hasMax) {
                    max = value;
                    hasMax = true;
                } else if (max < value)
                    max = value;
            }

        }

        options.put("max", max);
        options.put("min", min);

        domain.put(min).put(max);

        if (options.optBoolean("reverse", false)) {
            JSONUtil.reverse(domain);
        }

        options.put("domain", domain);

    }

}

From source file:org.loklak.api.iot.ImportProfileServlet.java

private void doSearch(Query post, HttpServletResponse response) throws IOException {
    String callback = post.get("callback", "");
    boolean minified = post.get("minified", false);
    boolean jsonp = callback != null && callback.length() > 0;
    String source_type = post.get("source_type", "");
    String screen_name = post.get("screen_name", "");
    String msg_id = post.get("msg_id", "");
    String detailed = post.get("detailed", "");
    // source_type either has to be null a a valid SourceType value
    if (!"".equals(source_type) && !SourceType.isValid(source_type)) {
        response.sendError(400, "your request must contain a valid source_type parameter.");
        return;//from  w w w  .  j  ava2 s .co  m
    }
    Map<String, String> searchConstraints = new HashMap<>();
    if (!"".equals(source_type)) {
        searchConstraints.put("source_type", source_type);
    }
    if (!"".equals(screen_name)) {
        searchConstraints.put("sharers", screen_name);
    }
    if (!"".equals(msg_id)) {
        searchConstraints.put("imported", msg_id);
    }
    Collection<ImportProfileEntry> entries = DAO.SearchLocalImportProfilesWithConstraints(searchConstraints,
            true);
    JSONArray entries_to_map = new JSONArray();
    for (ImportProfileEntry entry : entries) {
        JSONObject entry_to_map = entry.toJSON();
        if ("true".equals(detailed)) {
            String query = "";
            for (String msgId : entry.getImported()) {
                query += "id:" + msgId + " ";
            }
            DAO.SearchLocalMessages search = new DAO.SearchLocalMessages(query, Timeline.Order.CREATED_AT, 0,
                    1000, 0);
            entry_to_map.put("imported",
                    search.timeline.toJSON(false, "search_metadata", "statuses").get("statuses"));
        }
        entries_to_map.put(entry_to_map);
    }
    post.setResponse(response, "application/javascript");

    JSONObject m = new JSONObject(true);
    JSONObject metadata = new JSONObject();
    metadata.put("count", entries.size());
    metadata.put("client", post.getClientHost());
    m.put("search_metadata", metadata);
    m.put("profiles", entries_to_map);

    // write json
    response.setCharacterEncoding("UTF-8");
    PrintWriter sos = response.getWriter();
    if (jsonp)
        sos.print(callback + "(");
    sos.print(minified ? m.toString() : m.toString(2));
    if (jsonp)
        sos.println(");");
    sos.println();
}