Example usage for org.json JSONArray toString

List of usage examples for org.json JSONArray toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Make a JSON text of this JSONArray.

Usage

From source file:com.taxicop.client.NetworkUtilities.java

public static String process_upload() {
    Log.i(TAG, "process(): enviar datos al servidor");
    JSONArray elements = new JSONArray();
    Iterator<JsonData> i = adapter.iterator();
    String resp = "";
    try {/*from   ww  w  .  j a v  a2  s.  c  o  m*/
        if (elements == null || adapter == null || adapter.size() == 0)
            return "-1";
        elements.put(adapter.poll().toJSON_HEADER());
    } catch (JSONException ex) {
        Log.e("Json", "JSONException", ex);
    }
    Log.i(TAG, "process(): listo para enviar " + adapter.size() + " datos al servidor");
    while (i.hasNext()) {
        try {
            elements.put((adapter.poll().toJSON()));
        } catch (JSONException ex) {
            Log.e("Json", "JSONException", ex);
        }
    }
    request = elements.toString();
    try {
        Log.d(TAG, "send = " + request);
        resp = sendToServer(request, JSON_URI_UPLOAD);
        Log.d(TAG, "response: " + resp);
    } catch (Exception ex) {
        Log.e(TAG, "IOException", ex);
    }
    return resp;
}

From source file:com.taxicop.client.NetworkUtilities.java

public static String process_download() {
    Log.i(TAG, "process(): enviar datos al servidor");
    JSONArray elements = new JSONArray();
    Iterator<JsonData> i = adapter.iterator();
    String resp = "";
    try {//from w  w  w  .  ja v  a2s  .c  o m
        if (elements == null || adapter == null || adapter.size() == 0)
            return "-1";
        elements.put(adapter.poll().toJSON_HEADER());
        elements.put(adapter.poll().toJSON_DOWNLOAD());
    } catch (JSONException ex) {
        Log.e("Json", "JSONException", ex);
    }
    Log.i(TAG, "process(): listo para enviar " + adapter.size() + " datos al servidor");

    request = elements.toString();
    try {
        Log.d(TAG, "send = " + request);
        resp = sendToServer(request, JSON_URI_DOWNLOAD);
        Log.d(TAG, "response: " + resp);
    } catch (Exception ex) {
        Log.e(TAG, "IOException", ex);
    }
    return resp;
}

From source file:net.portalblockz.portalbot.webinterface.WebIntHandler.java

private String getJSONServers() {
    /*//from w  w  w  .  j  a  v  a  2s  . c om
    Server Host
    Channels
        Channel Name
        People
     */
    JSONArray array = new JSONArray();
    for (ConnectionPack pack : PortalBot.getInstance().getConnections()) {
        JSONObject server = new JSONObject();
        server.put("host", pack.getHost());
        //Make channels
        JSONArray channels = new JSONArray();
        for (Channel channel : pack.getSession().getChannels()) {
            JSONObject chnl = new JSONObject();
            chnl.put("name", channel.getName());
            chnl.put("motd", channel.getTopic());
            chnl.put("people", channel.getNicks());
            channels.put(chnl);
        }
        server.put("channels", channels);

        //Add other things?

        //Add connection to array
        array.put(server);
    }
    return array.toString();
}

From source file:com.webpagebytes.cms.engine.JSONToFromObjectConverter.java

public <T> String JSONStringFromListObjects(List<T> listObject) {
    org.json.JSONArray jsonArray = new org.json.JSONArray();
    for (Object obj : listObject) {
        org.json.JSONObject json = JSONFromObject(obj);
        jsonArray.put(json);/*  w w  w  . j a  va 2s.c o  m*/
    }
    return jsonArray.toString();
}

From source file:fr.pasteque.client.sync.SyncSend.java

private boolean nextTicketRush() {
    if (this.ticketOffset >= this.receipts.size()) {
        return false;
    }// w w w.  j a v  a 2  s.  c o  m
    JSONArray rcptsJSON = new JSONArray();
    for (int i = this.ticketOffset; i < this.receipts.size() && i < this.ticketOffset + TICKETS_BUFFER; i++) {
        Receipt r = this.receipts.get(i);
        if (Data.Customer.resolvedIds.size() > 0 && r.getTicket() != null
                && r.getTicket().getCustomer() != null) {
            String sId = Data.Customer.resolvedIds.get(r.getTicket().getCustomer().getId());
            if (sId != null)
                r.getTicket().getCustomer().setId(sId);
        }
        try {
            JSONObject o = r.toJSON(this.ctx);
            rcptsJSON.put(o);
        } catch (JSONException e) {
            Log.e(LOG_TAG, r.toString(), e);
            this.fail(e);
            return false;
        }
    }
    this.currentChunkSize = rcptsJSON.length();
    Map<String, String> postBody = SyncUtils.initParams(this.ctx, "TicketsAPI", "save");
    postBody.put("tickets", rcptsJSON.toString());
    postBody.put("cashId", this.cash.getId());
    URLTextGetter.getText(SyncUtils.apiUrl(this.ctx), null, postBody,
            new DataHandler(DataHandler.TYPE_RECEIPTS));
    return true;
}

From source file:uk.co.senab.photup.model.PhotoUpload.java

/**
 * Used only for ORMLite//from  ww  w  . j a va2  s.  c o m
 */
public String getTagJson() {
    if (getPhotoTagsCount() > 0) {
        JSONArray document = new JSONArray();
        for (PhotoTag tag : mTags) {
            try {
                document.put(tag.toJsonObject());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return document.toString();
    }
    return null;
}

From source file:org.sleeksnap.impl.History.java

/**
 * Save the history to a file//w ww  .j  a v  a  2 s .  c  om
 * 
 * @throws IOException
 *             If an error occurs saving the file
 * @throws JSONException
 */
private void save() throws IOException {
    final OutputStream output = new FileOutputStream(file);
    try {
        final JSONArray array = new JSONArray();
        for (final HistoryEntry e : history) {
            array.put(e.toJSONObject());
        }
        output.write(array.toString().getBytes());
    } finally {
        output.close();
    }
}

From source file:parser.GameDataService.java

public void searilizeToJson(String path, String file) {
    String JSON_FILE;/* ww  w. j  ava2  s .c om*/
    ArrayList<Object> gamedata = parse(path + file);
    int i = 0, j = 0;
    DataVO sheetData;
    ArrayList<Object> sheet;
    HashMap<String, Object> rowData;

    JSONArray sheetJsonArray;
    JSONObject sheetJsonObject = null;

    Iterator<String> iterator;

    for (i = 0; i < gamedata.size(); i++) {
        sheetData = (DataVO) gamedata.get(i);
        JSON_FILE = path + (sheetData.type + ".json");
        sheet = sheetData.data;

        sheetJsonArray = new JSONArray();

        for (j = 0; j < sheet.size(); j++) {
            rowData = (HashMap<String, Object>) sheet.get(j);

            iterator = rowData.keySet().iterator();
            sheetJsonObject = new JSONObject();
            while (iterator.hasNext()) {
                String key = (String) iterator.next();

                try {
                    sheetJsonObject.put(key, rowData.get(key));
                } catch (JSONException e) {
                }
            }

            sheetJsonArray.put(sheetJsonObject);

            try {
                FileWriter fstream = new FileWriter(JSON_FILE);
                BufferedWriter out = new BufferedWriter(fstream);
                out.write(sheetJsonArray.toString());
                out.close();
            } catch (IOException e) {
                System.out.println(JSON_FILE + "File Read Error:" + e.getMessage());

            }
        }

    }

}

From source file:com.rapid.actions.Datacopy.java

@Override
public String getJavaScript(RapidRequest rapidRequest, Application application, Page page, Control control,
        JSONObject jsonDetails) {//ww  w .j  a  v  a  2  s  .  c o m

    // the javascript we're making
    String js = "";

    // get the Rapid servlet
    RapidHttpServlet rapidServlet = rapidRequest.getRapidServlet();

    // get any copy type
    String copyType = getProperty("copyType");

    // set to replace if null (for backwards compatibility)
    if (copyType == null)
        copyType = "replace";

    // bulk copy is a special animal
    if ("bulk".equals(copyType)) {

        // check we have some data copies
        if (_dataCopies == null) {

            // data copies not found return a comment
            js = "// data copies not found for " + getId();

        } else {

            // compare against last getData call to avoid recalling
            String lastGetDataFunction = null;

            // loop them
            for (DataCopy dataCopy : _dataCopies) {

                // get the destination id
                String destinationId = dataCopy.getDestination();

                // check we got one
                if (destinationId.length() > 0) {

                    // get the get data function
                    String getDataFunction = Control.getDataJavaScript(rapidServlet.getServletContext(),
                            application, page, dataCopy.getSource(), dataCopy.getSourceField());

                    // add the getData if different from the last one
                    if (!getDataFunction.equals(lastGetDataFunction))
                        js += "var data = " + Control.getDataJavaScript(rapidServlet.getServletContext(),
                                application, page, dataCopy.getSource(), dataCopy.getSourceField()) + ";\n";

                    // remember this one
                    lastGetDataFunction = getDataFunction;

                    // split if by escaped .
                    String idParts[] = destinationId.split("\\.");
                    // if there is more than 1 part we are dealing with set properties, for now just update the destintation id
                    if (idParts.length > 1)
                        destinationId = idParts[0];

                    // first try and look for the control in the page
                    Control destinationControl = page.getControl(destinationId);
                    // assume we found it
                    boolean pageControl = true;
                    // check we got a control
                    if (destinationControl == null) {
                        // now look for the control in the application
                        destinationControl = application.getControl(rapidServlet.getServletContext(),
                                destinationId);
                        // set page control to false
                        pageControl = false;
                    }

                    // check we got one from either location
                    if (destinationControl == null) {

                        // data copies not found return a comment
                        js = "// data destination not found for " + destinationId;

                    } else {

                        // get the field
                        String destinationField = dataCopy.getDestinationField();
                        // clean up the field                        
                        if (destinationField == null)
                            destinationField = "";

                        // get any details we may have
                        String details = destinationControl.getDetailsJavaScript(application, page);

                        // if the idParts is greater then 1 this is a set property
                        if (idParts.length > 1) {

                            // if we have some details
                            if (details != null) {
                                // if this is a page control
                                if (pageControl) {
                                    // the details will already be in the page so we can use the short form
                                    details = destinationControl.getId() + "details";
                                }
                            }

                            // get the property from the second id part
                            String property = idParts[1];
                            // append the set property call
                            js += "setProperty_" + destinationControl.getType() + "_" + property + "(ev, '"
                                    + destinationControl.getId() + "', '" + destinationField + "', " + details
                                    + ", data, " + Boolean.parseBoolean(getProperty("changeEvents")) + ");\n";

                        } else {

                            // set details to empty string or clean up
                            if (details == null) {
                                details = "";
                            } else {
                                // if this is a page control
                                if (pageControl) {
                                    // the details will already be in the page so we can use the short form
                                    details = ",details:" + destinationControl.getId() + "details";
                                } else {
                                    // write the full details
                                    details = ",details:" + details;
                                }
                            }

                            // try and get the type
                            String type = dataCopy.getType();
                            // check it
                            if (type == null || "false".equals(type)) {
                                // update to empty string
                                type = "";
                            } else {
                                // update to comma-prefixed, string escaped
                                type = ",'" + type + "'";
                            }

                            // do the data copy
                            js += "Action_datacopy(ev, data, [{id:'" + destinationControl.getId() + "',type: '"
                                    + destinationControl.getType() + "',field:'" + destinationField + "'"
                                    + details + "}], " + Boolean.parseBoolean(getProperty("changeEvents"))
                                    + type + ");\n";

                        } // copy / set property check

                    } // destination control check            

                } // destination id check

            } // data copies loop

        } // data copies check

    } else {

        // get the data source
        String dataSourceId = getProperty("dataSource");

        // check there is a datasource
        if (dataSourceId == null) {

            // no data source return a comment
            js = "// no data source for action " + getId();

        } else {

            String dataSourceField = getProperty("dataSourceField");

            js = "var data = " + Control.getDataJavaScript(rapidServlet.getServletContext(), application, page,
                    dataSourceId, dataSourceField) + ";\n";

            // we're going to work with the data destinations in a json array
            JSONArray jsonDataDestinations = null;

            // assume we have no need for an outputs array
            boolean outputsArray = false;

            // try and get the data destinations from the properties into a json array, silently fail if not
            try {
                jsonDataDestinations = new JSONArray(getProperty("dataDestinations"));
            } catch (Exception e) {
            }

            if (jsonDataDestinations == null) {

                // data source destinations not found return a comment
                js = "// data source destinations not found for " + getId();

            } else {

                // prepare a string for the outputs array
                String jsOutputs = "";
                // loop the json data destination collection
                for (int i = 0; i < jsonDataDestinations.length(); i++) {

                    // try and make an output for this destination
                    try {

                        // retrieve this data destination
                        JSONObject jsonDataDesintation = jsonDataDestinations.getJSONObject(i);
                        // get the control id
                        String destinationId = jsonDataDesintation.getString("itemId");

                        // split by escaped .
                        String idParts[] = destinationId.split("\\.");
                        // if there is more than 1 part we are dealing with set properties, for now just update the destintation id
                        if (idParts.length > 1)
                            destinationId = idParts[0];

                        // first try and look for the control in the page
                        Control destinationControl = page.getControl(destinationId);
                        // assume we found it
                        boolean pageControl = true;
                        // check we got a control
                        if (destinationControl == null) {
                            // now look for the control in the application
                            destinationControl = application.getControl(rapidServlet.getServletContext(),
                                    destinationId);
                            // set page control to false
                            pageControl = false;
                        }

                        // check we got one from either location
                        if (destinationControl != null) {

                            // get the field
                            String destinationField = jsonDataDesintation.optString("field");
                            // clean up the field                        
                            if (destinationField == null)
                                destinationField = "";

                            // get any details we may have
                            String details = destinationControl.getDetailsJavaScript(application, page);

                            // if the idParts is greater then 1 this is a set property
                            if (idParts.length > 1) {

                                // if we have some details
                                if (details != null) {
                                    // if this is a page control
                                    if (pageControl) {
                                        // the details will already be in the page so we can use the short form
                                        details = destinationControl.getId() + "details";
                                    }
                                }

                                // get the property from the second id part
                                String property = idParts[1];
                                // append the set property call
                                js += "setProperty_" + destinationControl.getType() + "_" + property + "(ev,'"
                                        + destinationControl.getId() + "','" + destinationField + "'," + details
                                        + ",data);\n";

                            } else {

                                // we will need an outputs array
                                outputsArray = true;

                                // set details to empty string or clean up
                                if (details == null) {
                                    details = "";
                                } else {
                                    // if this is a page control
                                    if (pageControl) {
                                        // the details will already be in the page so we can use the short form
                                        details = ",details:" + destinationControl.getId() + "details";
                                    } else {
                                        // write the full details
                                        details = ",details:" + details;
                                    }
                                }

                                // add the properties we need as a js object it will go into the array
                                jsOutputs += "{id:'" + destinationControl.getId() + "',type: '"
                                        + destinationControl.getType() + "',field:'" + destinationField + "'"
                                        + details + "},";

                            }

                        }

                    } catch (JSONException ex) {

                        // data source destinations not found return a comment
                        js = "// error creating data output for " + getId() + " : " + ex.getMessage();

                    }
                }

                // if there was an outputs array 
                if (outputsArray) {

                    // trim the last comma
                    if (jsOutputs.length() > 0)
                        jsOutputs = jsOutputs.substring(0, jsOutputs.length() - 1);

                    // add to js as an array
                    js += "var outputs = [" + jsOutputs + "];\n";
                    // add the start of the call
                    js += "Action_datacopy(ev, data, outputs, "
                            + Boolean.parseBoolean(getProperty("changeEvents"));

                    // add the copy type to the js
                    js += ", '" + copyType + "'";
                    // check the copy type
                    if ("child".equals(copyType)) {
                        // no merge data object
                        js += ", null";
                        // look for a merge field
                        String childField = getProperty("childField");
                        // check if got we got one
                        if (childField == null) {
                            // call it child if not
                            js += ", 'child'";
                        } else {
                            // add it
                            js += ", '" + childField + "'";
                        }

                    } else if ("search".equals(copyType)) {

                        // get the search data
                        js += ", " + Control.getDataJavaScript(rapidServlet.getServletContext(), application,
                                page, getProperty("searchSource"), getProperty("searchSourceField"));
                        // look for a search field
                        String searchField = getProperty("searchField");
                        // add it if present
                        if (searchField != null)
                            js += ", '" + searchField + "'";
                        // look for a maxRows field
                        String maxRows = getProperty("maxRows");
                        // add it if present
                        if (maxRows != null)
                            js += "," + maxRows;

                    } else if ("trans".equals(copyType)) {

                        // assume the key fields are null
                        String keyFields = "null";

                        // try and fetch the key fields
                        try {
                            JSONArray jsonKeyFields = new JSONArray(getProperty("keyFields"));
                            keyFields = jsonKeyFields.toString();
                        } catch (JSONException ex) {
                            keyFields = "null /*" + ex.getMessage() + "*/";
                        }

                        // assume the ignore fields are null
                        String ignoreFields = "null";

                        // try and fetch the ignore fields, show message if issue
                        try {
                            JSONArray jsonIgnoreFields = new JSONArray(getProperty("ignoreFields"));
                            ignoreFields = jsonIgnoreFields.toString();
                        } catch (JSONException ex) {
                            ignoreFields = "null /*" + ex.getMessage() + "*/";
                        }

                        // add the details
                        js += ", null, null, {keyFields:" + keyFields + ",ignoreFields:" + ignoreFields + "}";

                    } // copy type

                    // close the copy data call
                    js += ");\n";

                } // outputs array

            } // data destinations check

        } // data source check

    } // bulk copy check

    return js;

}

From source file:com.dbmojo.QueryExecutor.java

/** Serialize the  result set to JSON. */
private String serializeToJson(ArrayList<HashMap> resList) throws JSONException {

    JSONArray resArray = new JSONArray();

    final int rlen = resList.size();
    for (int i = 0; i < rlen; i++) {
        JSONObject jObj = new JSONObject();
        final HashMap tHashMap = resList.get(i);

        if (tHashMap.containsKey("message")) {
            jObj.put("message", (String) tHashMap.get("message"));
        }//  www .  j ava2 s.  c  o  m

        if (tHashMap.containsKey("status")) {
            jObj.put("status", (String) tHashMap.get("status"));
        }

        if (tHashMap.containsKey("types")) {
            jObj.put("types", new JSONArray(((ArrayList) tHashMap.get("types")).toArray()));
        }

        if (tHashMap.containsKey("cols")) {
            jObj.put("cols", new JSONArray(((ArrayList) tHashMap.get("cols")).toArray()));
        }

        if (tHashMap.containsKey("rows")) {

            JSONArray tJarr = new JSONArray();
            final ArrayList rows = (ArrayList) tHashMap.get("rows");
            final int tlen = rows.size();

            for (int v = 0; v < tlen; v++) {
                tJarr.put(new JSONArray(((ArrayList) rows.get(v)).toArray()));
            }

            jObj.put("rows", tJarr);
        }

        resArray.put(jObj);
    }

    return resArray.toString();
}