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.google.android.apps.paco.ExperimentExecutorCustomRendering.java

private static String convertEventsToJsonString(final Experiment experiment, List<Event> events) {
    // TODO use jackson instead. But preserve these synthesized values for backward compatibility.
    final JSONArray experimentData = new JSONArray();
    for (Event event : events) {
        try {// w  w  w.  ja v a 2  s  .  c  om
            JSONObject eventObject = new JSONObject();
            boolean missed = event.getResponseTime() == null;
            eventObject.put("isMissedSignal", missed);
            if (!missed) {
                eventObject.put("responseTime", event.getResponseTime().getMillis());
            }

            boolean selfReport = event.getScheduledTime() == null;
            eventObject.put("isSelfReport", selfReport);
            if (!selfReport) {
                eventObject.put("scheduleTime", event.getScheduledTime().getMillis());
            }

            JSONArray responses = new JSONArray();
            for (Output response : event.getResponses()) {
                JSONObject responseJson = new JSONObject();
                Input input = experiment.getInputById(response.getInputServerId());
                if (input == null) {
                    continue;
                }
                responseJson.put("inputId", input.getServerId());
                // deprecate inputName in favor of name
                responseJson.put("inputName", input.getName());
                responseJson.put("name", input.getName());
                responseJson.put("responseType", input.getResponseType());
                responseJson.put("isMultiselect", input.isMultiselect());
                responseJson.put("prompt", getTextOfInputForOutput(experiment, response));
                responseJson.put("answer", response.getDisplayOfAnswer(input));
                // deprecated for answerRaw
                responseJson.put("answerOrder", response.getAnswer());
                responseJson.put("answerRaw", response.getAnswer());
                responses.put(responseJson);
            }

            eventObject.put("responses", responses);
            if (responses.length() > 0) {
                experimentData.put(eventObject);
            }
        } catch (JSONException jse) {
            // skip this event and do the next event.
        }
    }
    String experimentDataAsJson = experimentData.toString();
    return experimentDataAsJson;
}

From source file:com.tweetlanes.android.App.java

public void onPostSignIn(TwitterUser user, String oAuthToken, String oAuthSecret,
        SocialNetConstant.Type oSocialNetType) {

    if (user != null) {

        try {/*from   w  w  w . j  a  v  a 2 s .c  o  m*/

            final Editor edit = mPreferences.edit();
            String userIdAsString = Long.toString(user.getId());

            AccountDescriptor account = new AccountDescriptor(this, user, oAuthToken, oAuthSecret,
                    oSocialNetType);
            edit.putString(getAccountDescriptorKey(user.getId()), account.toString());

            String accountIndices = mPreferences.getString(SHARED_PREFERENCES_KEY_ACCOUNT_INDICES, null);
            JSONArray jsonArray;

            if (accountIndices == null) {
                jsonArray = new JSONArray();
                jsonArray.put(0, user.getId());
                mAccounts.add(account);
            } else {
                jsonArray = new JSONArray(accountIndices);
                boolean exists = false;
                for (int i = 0; i < jsonArray.length(); i++) {
                    String c = jsonArray.getString(i);
                    if (c.compareTo(userIdAsString) == 0) {
                        exists = true;
                        mAccounts.set(i, account);
                        break;
                    }
                }

                if (exists == false) {
                    jsonArray.put(userIdAsString);
                    mAccounts.add(account);
                }
            }

            accountIndices = jsonArray.toString();
            edit.putString(SHARED_PREFERENCES_KEY_ACCOUNT_INDICES, accountIndices);

            edit.commit();

            setCurrentAccount(user.getId());

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        updateTwitterAccountCount();
        if (TwitterManager.get().getSocialNetType() == oSocialNetType) {
            TwitterManager.get().setOAuthTokenWithSecret(oAuthToken, oAuthSecret, true);
        } else {
            TwitterManager.initModule(oSocialNetType,
                    oSocialNetType == SocialNetConstant.Type.Twitter ? ConsumerKeyConstants.TWITTER_CONSUMER_KEY
                            : ConsumerKeyConstants.APPDOTNET_CONSUMER_KEY,
                    oSocialNetType == SocialNetConstant.Type.Twitter
                            ? ConsumerKeyConstants.TWITTER_CONSUMER_SECRET
                            : ConsumerKeyConstants.APPDOTNET_CONSUMER_SECRET,
                    oAuthToken, oAuthSecret, getCurrentAccountKey(), mConnectionStatusCallbacks);
        }
    }
}

From source file:com.sublimis.urgentcallfilter.MyPreference.java

public static void setData(JSONArray data) {
    String output = null;// ww w . j a  va  2 s  .c o m

    if (data != null)
        output = data.toString();

    setStringPref(R.string.pref_database_key, output);
}

From source file:com.google.enterprise.connector.ldap.LdapConnectorConfig.java

/**
 * Returns the string that represents the selected attributes in a json
 * understandable way. /* ww w.  j a v a2 s  .c o m*/
 * First tries to search if the json string is passed by the config. If it is
 * not found then we try to create the json string from original LDAP
 * configuration format.  The original format is individual keys for 
 * each value.
 * @return String json parsable string representation of the selected 
 *         attributes 
 */
static String getJsonStringForSelectedAttributes(Map<String, String> config) {
    String schemaValue = config.get(ConfigName.SCHEMAVALUE.toString());
    if (schemaValue == null || schemaValue.equals("[]")) {
        LOG.info("Trying to recover attributes from individual checkboxes");
        StringBuffer schemaKey = new StringBuffer();
        schemaKey.append(ConfigName.SCHEMA.toString()).append("_").append("\\d");
        Pattern keyPattern = Pattern.compile(schemaKey.toString());
        Set<String> configKeySet = config.keySet();
        JSONArray arr = new JSONArray();
        for (String configKey : configKeySet) {
            Matcher matcher = keyPattern.matcher(configKey);
            if (matcher.find()) {
                String schemaAttribute = config.get(configKey);
                if (schemaAttribute != null && schemaAttribute.trim().length() != 0) {
                    arr.put(config.get(configKey));
                }
            }
        }
        if (arr.length() != 0) {
            schemaValue = arr.toString();
        } else {
            schemaValue = "";
        }
    }
    LOG.info("The appended string for selected attributes is: " + schemaValue);
    return schemaValue;
}

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

/**
 * Sends new customer to server./*  w  w w  .  j a  v  a  2  s  . c o m*/
 * @return true if customers were send, false otherwise
 */
private boolean sendCustomer() {
    if (Data.Customer.resolvedIds.size() > 0) {
        Log.i(LOG_TAG, "Customer Sync: There are saved local customer ids");
    }
    if (!this.sendCustomer) {
        SyncUtils.notifyListener(this.listener, SyncSend.CUSTOMER_SYNC_DONE);
        instance.nextArchive();
        return false;
    }
    JSONArray cstJArray = new JSONArray();
    for (Customer c : Data.Customer.createdCustomers) {
        try {
            // requiered hack to avoid errors. Prepaid is local storage
            // use but the prepaid amount will be calculated from tickets
            // lines by Pastequ-API
            double storedCustomerPrepaid = c.getPrepaid();
            c.setPrepaid(0);
            JSONObject o = c.toJSON();
            cstJArray.put(o);
            c.setPrepaid(storedCustomerPrepaid);
        } catch (JSONException e) {
            Log.d(LOG_TAG, c.toString(), e);
            SyncUtils.notifyListener(this.listener, SyncSend.CUSTOMER_SYNC_FAILED);
            return false;
        }
    }
    this.subprogress++;
    this.refreshFeedback();
    Map<String, String> postBody = SyncUtils.initParams(this.ctx, "CustomersAPI", "save");
    postBody.put("customers", cstJArray.toString());
    URLTextGetter.getText(SyncUtils.apiUrl(this.ctx), null, postBody, new CustHandler(this, this.listener));
    return true;
}

From source file:org.skt.runtime.api.PluginResult.java

public PluginResult(Status status, JSONArray message) {
    this.status = status.ordinal();
    this.message = message.toString();
}

From source file:santandersensors_server.ConsoleThread.java

@Override
public void run() {
    try {/*from w  w w. j ava2  s. c  o  m*/
        output = new PrintWriter(S.getOutputStream(), true);
        JSONArray tagsSensor = this.client.getJsonArrayOnceFromCollection(this.tagsColl, "tags");
        output.println(tagsSensor.toString());
        JSONArray typeSensor = this.client.getJsonArrayOnceFromCollection(this.typeColl, "type");
        output.println(typeSensor.toString());
        while (true) {
            this.input = new BufferedReader(new InputStreamReader(S.getInputStream()));
            this.StreamParse(this.input.readLine());
            switch (scelta) {
            case 1:
                this.sensorvalue = this.mapReduceOBJ.getAverageValue(SensorName, Tags, ID, SensorCutValue);
                this.sendResult();
                break;
            case 2:
                this.sensorvalue = this.mapReduceOBJ.getAverageValue(SensorName, Tags, ID, SensorCutValue,
                        SensorDateTime);
                this.sendResult();
                break;
            case 3:
                this.sensorvalue = this.mapReduceOBJ.getAverageValue(SensorName, Tags, SensorCutValue,
                        CoordinateCenter, Radius);
                this.sendResult();
                break;
            case 4:
                this.sensorvalue = this.mapReduceOBJ.getAverageValue(SensorName, Tags, SensorCutValue,
                        SensorDateTime, CoordinateCenter, Radius);
                this.sendResult();
                break;
            case 5:
                this.sensorvalue = this.mapReduceOBJ.getBUSInfo(ID, SensorDateTime);
                this.sendResult();
            }
        }

    } catch (Exception e) {
        System.out.print("(" + new GregorianCalendar().getTime() + ") -> ");
        System.out.print(" fatal error: " + e + "\n");
        this.error();
    }
}

From source file:com.marpies.ane.facedetection.functions.DetectFacesFunction.java

private void dispatchResponse(JSONArray facesResult, int callbackId) {
    JSONObject response = new JSONObject();
    try {//from  w w  w. j  a va 2  s. c o m
        response.put("faces", facesResult.toString());
        response.put("callbackId", callbackId);
        AIR.dispatchEvent(FaceDetectionEvent.FACE_DETECTION_COMPLETE, response.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        AIR.log("Error creating JSON response");
        AIR.dispatchEvent(FaceDetectionEvent.FACE_DETECTION_ERROR,
                StringUtils.getEventErrorJSON(callbackId, "Error creating JSON response"));
    }
}

From source file:org.exoplatform.social.portlet.UISpacesToolBarPortlet.java

@Override
public void serveResource(WebuiRequestContext context) throws Exception {
    super.serveResource(context);

    ResourceRequest req = context.getRequest();
    String id = req.getResourceID();

    JSONArray jsChilds = getChildrenAsJSON(getNodeFromResourceID(id));
    if (jsChilds == null) {
        return;//from   w  ww . j  a va 2s .co  m
    }

    MimeResponse res = context.getResponse();
    res.setContentType("text/json");
    res.getWriter().write(jsChilds.toString());
}

From source file:de.joinout.criztovyl.tools.json.JSONFile.java

/**
 * Loads the JSON data from the {@link JSONArray}.
 * //w w w. j  a v a 2 s. c om
 * @param path
 *            the path to the JSON file
 * @param json
 *            the JSON object
 */
public JSONFile(Path path, JSONArray json) {

    logger = LogManager.getLogger();

    this.path = path;
    data = json.toString();
}