Example usage for org.json JSONStringer toString

List of usage examples for org.json JSONStringer toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Return the JSON text.

Usage

From source file:cc.metapro.openct.utils.ExcelHelper.java

public static String tableToJson(@NonNull String table) throws JSONException {
    String[] rows = table.split("\n");
    String[][] tableContents = new String[rows.length][];
    int i = 0;/*from  w w  w.  ja  va 2 s .  com*/
    for (String row : rows) {
        String[] cols = row.split("\t");
        tableContents[i++] = cols;
    }

    String[] headers = null;
    if (tableContents.length > 0) {
        headers = tableContents[0];
    }
    if (headers == null) {
        return "";
    }

    JSONStringer stringer = new JSONStringer();
    stringer.array();
    for (i = 1; i < tableContents.length; i++) {
        stringer.object();
        for (int j = 0; j < tableContents[i].length && j < headers.length; j++) {
            stringer.key(headers[j].trim()).value(tableContents[i][j]);
        }
        stringer.endObject();
    }
    stringer.endArray();

    return stringer.toString();
}

From source file:org.sc.probro.servlets.TextQueryServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from  www. jav a 2 s.com*/
        String searchTerm = getRequiredParam(request, "search", String.class);
        String contentType = getContentType(request);
        String[] ontologies = getOptionalParam(request, "ontology_id", String[].class);
        UserCredentials user = new UserCredentials();

        Broker broker = getBroker();
        try {
            SearchResult[] results = broker.query(user, searchTerm, ontologies);

            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType(contentType);

            if (contentType.equals(CONTENT_TYPE_JSON)) {

                JSONStringer stringer = new JSONStringer();
                stringer.array();
                for (SearchResult res : results) {
                    res.stringJSON(stringer);
                }
                stringer.endArray();

                response.getWriter().println(stringer.toString());

            } else if (contentType.equals(CONTENT_TYPE_HTML)) {

                PrintWriter writer = response.getWriter();
                writer.println("<table>");
                writer.println("<tr>" + "<th>ID</th>" + "<th>Type</th>" + "<th>Descriptions</th>"
                        + "<th>Accessions</th>" + "</tr>");
                for (SearchResult res : results) {
                    writer.println(renderHitAsHTML(res));
                }
                writer.println("</table>");

            } else {
                throw new BadRequestException(String.format("Unsupported content type: %s", contentType));
            }

        } catch (JSONException e) {
            throw new BrokerException(e);

        } finally {
            broker.close();
        }

    } catch (BrokerException e) {
        handleException(response, e);
        return;
    }

}

From source file:com.vaynberg.wicket.select2.Settings.java

public CharSequence toJson() {
    try {//from w  ww  .j  av  a 2 s . c  om
        JSONStringer writer = new JSONStringer();
        writer.object();
        Json.writeObject(writer, "minimumInputLength", minimumInputLength);
        Json.writeObject(writer, "minimumResultsForSearch", minimumResultsForSearch);
        Json.writeObject(writer, "maximumSelectionSize", maximumSelectionSize);
        Json.writeObject(writer, "placeholder", placeholder);
        Json.writeObject(writer, "allowClear", allowClear);
        Json.writeObject(writer, "multiple", multiple);
        Json.writeObject(writer, "closeOnSelect", closeOnSelect);
        Json.writeFunction(writer, "id", id);
        Json.writeFunction(writer, "matcher", matcher);
        Json.writeFunction(writer, "tokenizer", tokenizer);
        Json.writeFunction(writer, "formatSelection", formatSelection);
        Json.writeFunction(writer, "formatResult", formatResult);
        Json.writeFunction(writer, "formatNoMatches", formatNoMatches);
        Json.writeFunction(writer, "formatInputTooShort", formatInputTooShort);
        Json.writeFunction(writer, "formatResultCssClass", formatResultCssClass);
        Json.writeFunction(writer, "formatSelectionTooBig", formatSelectionTooBig);
        Json.writeFunction(writer, "formatLoadMore", formatLoadMore);
        Json.writeFunction(writer, "formatSearching", formatSearching);
        Json.writeFunction(writer, "createSearchChoice", createSearchChoice);
        Json.writeFunction(writer, "initSelection", initSelection);
        Json.writeFunction(writer, "query", query);
        Json.writeObject(writer, "width", width);
        Json.writeObject(writer, "openOnEnter", openOnEnter);
        Json.writeObject(writer, "containerCss", containerCss);
        Json.writeObject(writer, "containerCssClass", containerCssClass);
        Json.writeObject(writer, "dropdownCss", dropdownCss);
        Json.writeObject(writer, "dropdownCssClass", dropdownCssClass);
        Json.writeObject(writer, "separator", separator);
        Json.writeObject(writer, "tokenSeparators", tokenSeparators);
        writer.key("ajax");
        ajax.toJson(writer);

        Json.writeFunction(writer, "data", data);
        Json.writeFunction(writer, "tags", tags);
        writer.endObject();

        return writer.toString();
    } catch (JSONException e) {
        throw new RuntimeException("Could not convert Select2 settings object to Json", e);
    }
}

From source file:hu.bme.iit.quiz.endpoint.PollEndpoint.java

private String createFollowersUpdateString(Integer presentationID) {
    JSONStringer creator = new JSONStringer();
    creator.object().key("type").value("FOLLOWERSUPDATE").key("followers").array();
    Map<String, User> users = quizzesInOngoingPhase.get(presentationID).getFollowers();
    for (String key : users.keySet()) {
        User user = users.get(key);// ww w  .  j av a2 s . c o  m
        creator.object().key("username").value(user.getLogin()).endObject();
    }
    creator.endArray().endObject();
    return creator.toString();
}

From source file:hu.bme.iit.quiz.endpoint.PollEndpoint.java

private String createQuizQuestionUpdateString(Integer presentationID, Integer questionID) {
    logger.debug("sendQuizQestion createQuizQuestionUpdateString start: questionID: " + questionID);
    JSONStringer creator = new JSONStringer();
    Question question = quizzesInOngoingPhase.get(presentationID).getQuestionData(questionID);
    creator.object().key("type").value("QUESTION").key("questionTitle").value(question.getQuestionTitle())
            .key("questionID").value(questionID).key("questionBody").value(question.getQuestionBody())
            .key("options").array();
    for (QuestionOption option : question.getQuestionContent().getQuestionOption()) {
        creator.object().key("optionBody").value(option.getQuestionOptionBody()).endObject();
    }//from  w  ww.  j  ava 2 s .co  m
    creator.endArray().endObject();
    logger.debug("sendQuizQestion createQuizQuestionUpdateString finish");
    return creator.toString();
}

From source file:hu.bme.iit.quiz.endpoint.PollEndpoint.java

private String createUserAnswerUpdateString(Integer presentationID) {
    JSONStringer creator = new JSONStringer();
    QuizRoom quiz = quizzesInOngoingPhase.get(presentationID);
    creator.object().key("type").value("ANSWERUPDATE").key("answers").array();
    for (String secretkey : userAnswers.keySet()) {
        User user = EndpointUtil.getUserByKey(secretkey);
        creator.object().key("username").value(user.getLogin()).key("selected").value(
                userAnswers.get(secretkey)[quizzesInOngoingPhase.get(presentationID).getActualQuestion()])
                .endObject();/*from   ww w  .ja va 2  s  .  co m*/
    }
    creator.endArray().endObject();
    return creator.toString();
}

From source file:hu.bme.iit.quiz.endpoint.PollEndpoint.java

private String createQuizCorrectionString(List<Integer> corrects) {
    JSONStringer creator = new JSONStringer();
    creator.object().key("type").value("CORRECTION").key("corrects").array();
    for (Integer correct : corrects) {
        creator.object().key("optionID").value(correct).endObject();
    }// w ww  .j a v  a2  s .c o m
    creator.endArray().endObject();
    return creator.toString();
}

From source file:org.sc.probro.servlets.RequestListServlet.java

public static String formatRequestsAsJSON(Request[] reqs) throws BrokerException {
    JSONStringer stringer = new JSONStringer();
    try {//from   w  w  w.  j  av  a2  s.  com
        stringer.object();

        stringer.key("vals");
        BrokerData.stringJSONArray(stringer, reqs);

        stringer.endObject();
    } catch (JSONException e) {
        throw new BrokerException(e);
    }

    return stringer.toString();
}

From source file:org.qi4j.index.rdf.query.internal.RdfQueryParserImpl.java

private String createAndEscapeJSONString(Object value, PropertyReference<?> propertyRef) throws JSONException {
    ValueType type = ValueTypeFactory.instance().newValueType(value.getClass(), propertyRef.propertyType(),
            propertyRef.propertyDeclaringType());

    JSONStringer json = new JSONStringer();
    json.array();//from ww  w.  j av a 2 s .c o  m
    this.createJSONString(value, type, json);
    json.endArray();
    String result = json.toString();
    result = result.substring(1, result.length() - 1);

    result = this.escapeJSONString(result);

    return result;
}

From source file:com.yahoo.egads.data.JsonEncoder.java

public static String toJson(Object object) throws Exception {
    JSONStringer jsonOut = new JSONStringer();
    toJson(object, jsonOut);/*from   w ww  .j a  v  a2  s  .  c  om*/
    return jsonOut.toString();
}