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:edu.asu.msse.sgowdru.moviemediaplayerrpc.AsyncCollectionConnect.java

@Override
protected JSONObject doInBackground(MethodInformation... aRequest) {
    try {// w  ww .  j  a v  a  2s.  co  m
        JSONArray ja = new JSONArray(aRequest[0].params);
        String requestData = "{ \"jsonrpc\":\"2.0\", \"method\":\"" + aRequest[0].method + "\", \"params\":"
                + ja.toString() + ",\"id\":3}";
        JsonRPCRequestViaHttp conn = new JsonRPCRequestViaHttp((new URL(aRequest[0].urlString)));

        // If the method name is getTitles, retun json array of movie names
        if (aRequest[0].method.equals("getTitles")) {
            String resultStr = conn.call(requestData);
            System.out.println(resultStr);
            aRequest[0].resultAsJson = resultStr;
            json = new JSONObject(resultStr);
        }
        // If the method name is "get" return the movie details for the particular parameter that is passed to it
        else if (aRequest[0].method.equals("get")) {
            String resultStr = conn.call(requestData);
            System.out.println(resultStr);
            aRequest[0].resultAsJson = resultStr;
            json = new JSONObject(resultStr);
        }
    } catch (Exception ex) {
        android.util.Log.d(this.getClass().getSimpleName(), "exception in remote call " + ex.getMessage());
    }
    // Return JSON object in both the cases
    return json;
}

From source file:com.jlt.patadata.WaitingFragment.java

@Override
// begin onStart//w ww .  j a  v  a  2 s  . co m
public void onStart() {

    // 0. super things
    // 1. use the Volley singleton to attempt to get the JSON from World Bank
    // 1a. create a JSON array request based on the URL
    // 1a1.if the request is successful
    // 1a1a. store the response string for use across fragments
    // 1a1b. start the fragment for displaying datasets in chart form
    // 1b2. if the request has failed
    // 1b2a. start the fragment for showing an error
    // 1c. add the request to the request queue

    // 0. super things

    super.onStart();

    // 1. use the Volley singleton to attempt to get the JSON from World Bank

    // 1a. create a JSON array request based on the URL

    // begin JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(

            Request.Method.GET,

            requestURLListener.getRequestURL(),

            null,

            // begin new Response.Listener< JSONArray >
            new Response.Listener<JSONArray>() {

                @Override
                // begin onResponse
                public void onResponse(JSONArray response) {

                    // 1a1.if the request is successful
                    // 1a1a. store the response string for use across fragments

                    responseJSONListener.onSetResponseJSON(response.toString());

                    Log.e("onResponse: ", response.toString());

                    // 1a1b. start the fragment for displaying datasets in chart form

                    FragmentManager fragmentManager = getActivity().getSupportFragmentManager();

                    fragmentManager

                            .beginTransaction()

                            .setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left)

                            .replace(R.id.m_fl_content, new ChartDisplayDatasetFragment())

                            .addToBackStack(MainActivity.FRAGMENT_CHART_DISPLAY_DATASET)

                            .commit();

                } // end onResponse

            }, // end new Response.Listener< JSONArray >

            // begin new Response.ErrorListener
            new Response.ErrorListener() {

                @Override
                // begin onErrorResponse
                public void onErrorResponse(VolleyError error) {

                    // 1b2. if the request has failed

                    // 1b2a. start the fragment for showing an error

                    FragmentManager fragmentManager = getFragmentManager();

                    fragmentManager

                            .beginTransaction()

                            .setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_left)

                            .replace(R.id.m_fl_content, new ErrorFragment())

                            .commit();

                } // end onErrorResponse

            } // end new Response.ErrorListener

    ); // end JsonArrayRequest jsonArrayRequest = new JsonArrayRequest

    // 1c. add the request to the request queue

    VolleySingleton.getInstance(getActivity()).addToRequestQueue(jsonArrayRequest);

}

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

protected String serialize(Collection<String> values) {
    if (values == null) {
        return null;
    }/*from   w w  w  .j  a  va2  s  .  c om*/
    JSONArray jsonArray = new JSONArray();
    for (String cohort : values) {
        jsonArray.put(cohort);
    }
    return jsonArray.toString();
}

From source file:com.hp.ov.sdk.rest.http.core.client.HttpRestClient.java

/**
 * Send the request to OV and read the response.
 *
 * @param restParams connection parameters.
 * @param//from  w w w . java2  s  . c o m
 *  jsonObject request body.
 *
 * @return
 *  A string representing the response data.
 * @throws
 *  SDKBadRequestException on unsupported method (PUT, GET..)
 **/
public String sendRequest(RestParams restParams, JSONArray jsonObject) throws SDKBadRequestException {
    return processRequestType(restParams, jsonObject.toString(), false);
}

From source file:org.cgiar.ilri.odk.pull.backend.services.FetchFormDataService.java

/**
 * This method is called whenever the service is called. Note that the service might have
 * already been running when it was called
 *
 * @param intent The intent used to call the service
 *//*from w  w w . jav a  2  s  . com*/
@Override
protected void onHandleIntent(Intent intent) {
    formName = intent.getStringExtra(KEY_FORM_NAME);
    if (formName != null) {
        //fetch data on the form
        try {
            String jsonString = DataHandler.sendDataToServer(this, null,
                    DataHandler.URI_FETCH_FORM_DATA + URLEncoder.encode(formName, "UTF-8"));
            if (jsonString != null) {
                try {
                    JSONObject jsonObject = new JSONObject(jsonString);
                    JSONObject fileData = jsonObject.getJSONObject("files");
                    Iterator<String> keys = fileData.keys();
                    String fetchedFilesString = "";
                    while (keys.hasNext()) {
                        String currFileName = keys.next();
                        Log.d(TAG, "Processing " + currFileName);
                        JSONArray currFileData = fileData.getJSONArray(currFileName);
                        if (currFileName.equals(Form.DEFAULT_CSV_FILE_NAME)) {
                            Log.d(TAG, "Treating " + currFileName + " like a itemset file");
                            Log.d(TAG, currFileName + " data = " + currFileData.toString());
                            String csv = getCSVString(currFileData);
                            if (csv != null) {
                                saveCSVInFile(currFileName + Form.SUFFIX_CSV, csv);
                                fetchedFilesString = fetchedFilesString + "\n" + " - " + currFileName
                                        + Form.SUFFIX_CSV;
                            } else {
                                Log.w(TAG, Form.DEFAULT_CSV_FILE_NAME
                                        + " from the server is null. Unable to save this on the device");
                                Toast.makeText(FetchFormDataService.this,
                                        getResources().getText(R.string.unable_fetch_data_for) + " "
                                                + currFileName,
                                        Toast.LENGTH_LONG).show();

                            }
                        } else {
                            Log.d(TAG, "Treating " + currFileName + " like an external data file");
                            boolean dataDumped = saveDataInDb(currFileName, currFileData);
                            String csv = getCSVString(currFileData);
                            if (csv != null) {
                                if (dataDumped) {
                                    saveCSVInFile(currFileName + Form.SUFFIX_CSV + Form.SUFFIX_IMPORTED, csv);
                                    fetchedFilesString = fetchedFilesString + "\n" + " - " + currFileName
                                            + Form.SUFFIX_DB;
                                    fetchedFilesString = fetchedFilesString + "\n" + " - " + currFileName
                                            + Form.SUFFIX_CSV + Form.SUFFIX_IMPORTED;
                                } else {
                                    saveCSVInFile(currFileName + Form.SUFFIX_CSV, csv);
                                    fetchedFilesString = fetchedFilesString + "\n" + " - " + currFileName
                                            + Form.SUFFIX_CSV;
                                }
                            } else {
                                Log.w(TAG, currFileName
                                        + " from the server is null. Unable to save this on the device");
                                Toast.makeText(FetchFormDataService.this,
                                        getResources().getText(R.string.unable_fetch_data_for) + " "
                                                + currFileName,
                                        Toast.LENGTH_LONG).show();
                            }
                        }
                    }
                    DataHandler.updateFormLastUpdateTime(FetchFormDataService.this, formName);
                    if (fetchedFilesString.length() > 0) {//only show the notification if at least one file updated
                        updateNotification(formName, getString(R.string.fetched_data),
                                getString(R.string.the_following_files_were_added) + fetchedFilesString);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e(TAG,
                        "Data from server null. Something happened while trying to fetch csv for " + formName);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    } else {
        Log.w(TAG, "Form name from intent bundle was null, doing nothing");
    }
}

From source file:com.aokp.romcontrol.github.tasks.GetJSONChangelogTask.java

protected Void doInBackground(Void... unused) {
    HttpClient httpClient = null;/*  w ww  .  j  a v  a 2  s . c  o  m*/
    try {
        httpClient = new DefaultHttpClient();
        String url = String.valueOf(STATIC_DEBUG ? "https://raw.github.com/JBirdVegas/tests/master/example.json"
                : mConfig.CHANGELOG_JSON);
        HttpGet requestWebsite = new HttpGet(url);
        Log.d(TAG, "attempting to connect to: " + url);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        JSONArray projectCommitsArray = new JSONArray(httpClient.execute(requestWebsite, responseHandler));

        // debugging
        if (DEBUG)
            Log.d(TAG, "projectCommitsArray.length() is: " + projectCommitsArray.length());
        if (Config.StaticVars.JSON_SPEW)
            Log.d(TAG, "projectCommitsArray.toString() is: " + projectCommitsArray.toString());

        final ChangelogObject commitObject = new ChangelogObject(new JSONObject());
        for (int i = 0; i < projectCommitsArray.length(); i++) {
            JSONObject projectsObject = (JSONObject) projectCommitsArray.get(i);
            PreferenceScreen newCommitPreference = mCategory.getPreferenceManager()
                    .createPreferenceScreen(mContext);
            commitObject.reParse(projectsObject);
            newCommitPreference.setTitle(commitObject.getSubject());
            newCommitPreference.setSummary(commitObject.getBody());
            newCommitPreference.setKey(commitObject.getCommitHash());
            newCommitPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    mAlertDialog.setCommitAndShow(commitObject);
                    return false;
                }
            });
            mCategory.addPreference(newCommitPreference);
        }
    } catch (HttpResponseException httpError) {
        Log.e(TAG, "bad HTTP response:", httpError);
    } catch (ClientProtocolException e) {
        Log.d(TAG, "client protocal exception:", e);
    } catch (JSONException e) {
        Log.d(TAG, "bad json interaction:", e);
    } catch (IOException e) {
        Log.d(TAG, "io exception:", e);
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return null;
}

From source file:net.iubris.ipc_d3.cap.CamelizeSomeFieldsAndExtractInformazioniStoricheDates.java

public static void main(String[] args) {
    try {// w  ww .  j  av a2s  . c om
        //         String input = args[0];
        String input = "../../data/data_totale.csv";
        String csvString = FileUtils.readFile(input, Charset.defaultCharset());

        csvString.replace("\"\"\"", "\"");
        JSONArray adjustedTimeAndTipiSpecifici = new CamelizeSomeFieldsAndExtractInformazioniStoricheDates()
                .adjustTimeAndTipiSpecifici(csvString);
        String adjustedTimeAndTipiSpecificiString = adjustedTimeAndTipiSpecifici.toString();
        System.out.println(adjustedTimeAndTipiSpecificiString);
        FileUtils.writeToFile(adjustedTimeAndTipiSpecificiString, "../data_totale_camelized_some_fields.json");

    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:com.util.httpAccount.java

public Account getAccountObject(String tel) {
    String telefono = tel.replace("-", "");
    System.out.println("OBTENER SOLO UN ARRAY DE CADENA JSON");
    //String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/50241109321.json";
    String myURL = "http://192.168.5.44/app_dev.php/cus/getaccount/" + telefono + ".json";
    System.out.println("Requested URL:" + myURL);
    StringBuilder sb = new StringBuilder();
    URLConnection urlConn = null;
    InputStreamReader in = null;/* w  w  w .j  av  a 2  s . c  o m*/
    Account account = new Account();
    try {
        URL url = new URL(myURL);
        urlConn = url.openConnection();
        if (urlConn != null) {
            urlConn.setReadTimeout(60 * 1000);
            if (urlConn != null && urlConn.getInputStream() != null) {
                in = new InputStreamReader(urlConn.getInputStream(), Charset.defaultCharset());

                BufferedReader bufferedReader = new BufferedReader(in);
                if (bufferedReader != null) {
                    int cp;
                    while ((cp = bufferedReader.read()) != -1) {
                        sb.append((char) cp);
                    }
                    bufferedReader.close();
                }
            }

            String jsonResult = sb.toString();
            // System.out.println(sb.toString());
            //System.out.println("\n\n--------------------OBTENEMOS OBJETO JSON NATIVO DE LA PAGINA, USAMOS EL ARRAY DATA---------------------------\n\n");
            JSONObject objJason = new JSONObject(jsonResult);
            JSONArray dataJson = new JSONArray();
            dataJson = objJason.getJSONArray("data");

            //System.out.println("objeto normal 1 "+dataJson.toString());
            //
            //
            // System.out.println("\n\n--------------------CREAMOS UN STRING JSON2 REEMPLAZANDO LOS CORCHETES QUE DAN ERROR---------------------------\n\n");
            String jsonString2 = dataJson.toString();
            String temp = dataJson.toString();
            temp = jsonString2.replace("[", "");
            jsonString2 = temp.replace("]", "");
            // System.out.println("new json string"+jsonString2);

            JSONObject objJson2 = new JSONObject(jsonString2);
            // System.out.println("el objeto simple json es " + objJson2.toString());

            // System.out.println("\n\n--------------------CREAMOS UN OBJETO JSON CON EL ARRAR ACCOUN---------------------------\n\n");
            String account1 = objJson2.optString("account");
            // System.out.println(account1);
            JSONObject objJson3 = new JSONObject(account1);
            //   System.out.println("el ULTIMO OBJETO SIMPLE ES  " + objJson3.toString());
            //   System.out.println("\n\n--------------------EMPEZAMOS A RECIBIR LOS PARAMETROS QUE HAY EN EL OBJETO JSON---------------------------\n\n");
            String firstName = objJson3.getString("first_name");
            System.out.println(firstName);
            System.out.println(objJson3.get("language_id"));
            //  System.out.println("\n\n--------------------TRATAMOS DE PASAR TODO EL ACCOUNT A OBJETO JAVA---------------------------\n\n");
            Gson gson = new Gson();
            account = gson.fromJson(objJson3.toString(), Account.class);
            //System.out.println(account.getFirst_name());
            // System.out.println(account.getCreation());
            account.setLanguaje_id(objJson3.get("language_id").toString());
            account.setId(objJson3.get("id").toString());
            account.setBalance(objJson3.get("balance").toString());
            System.out.println("el id del account es " + account.getId());

        } else {
            System.out.print("no se pudo conectar con el servidor");
            account = null;
        }

        in.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Exception while calling URL:" + myURL, e);
    }

    return account;
}

From source file:damo.three.ie.prepay.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {

    Context context = getApplicationContext();
    try {//  w  w w . j a va2s  .  c o  m
        Log.d(Constants.TAG, "Fetching usages from service.");
        UsageFetcher usageFetcher = new UsageFetcher(context, true);
        JSONArray usages = usageFetcher.getUsages();

        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences sharedUsagePref = context.getSharedPreferences("damo.three.ie.previous_usage",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedUsagePref.edit();
        editor.putLong("last_refreshed_milliseconds", new DateTime().getMillis());
        editor.putString("usage_info", usages.toString());
        editor.commit();

        // Register alarms for newly refreshed usages in background
        boolean notificationsEnabled = sharedPref.getBoolean("notification", true);
        List<UsageItem> usageItems = JSONUtils.jsonToUsageItems(usages);
        List<BasicUsageItem> basicUsageItems = UsageUtils.getAllBasicItems(usageItems);
        UsageUtils.registerInternetExpireAlarm(context, basicUsageItems, notificationsEnabled, true);

    } catch (Exception e) {
        // Try again at 7pm, unless its past 7pm. Then forget and let tomorrow's alarm do the updating.
        // Still trying to decide if I need a more robust retry mechanism.
        Log.d(Constants.TAG, "Caught exception: " + e.getLocalizedMessage());
        Calendar calendar = Calendar.getInstance();
        if (calendar.get(Calendar.HOUR_OF_DAY) < Constants.HOUR_TO_RETRY) {
            Log.d(Constants.TAG, "Scheduling a re-try for 7pm");
            calendar.set(Calendar.HOUR_OF_DAY, Constants.HOUR_TO_RETRY);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);

            Intent receiver = new Intent(context, UpdateReceiver.class);
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            // Using different request code to 0 so it won't conflict with other alarm below.
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 3, receiver,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            // Keeping efficiency in mind:
            // http://developer.android.com/reference/android/app/AlarmManager.html#ELAPSED_REALTIME
            am.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
        }
    } finally {
        Log.d(Constants.TAG, "Finish UpdateService");
        UpdateReceiver.completeWakefulIntent(intent);
    }
}

From source file:org.seadpdt.impl.SearchServiceImpl.java

private Response getAllPublishedROs(Document filter, Date start, Date end, String creatorRegex) {
    FindIterable<Document> iter = publicationsCollection.find(filter);
    setROProjection(iter);// w  w w .jav  a 2 s  . c om
    MongoCursor<Document> cursor = iter.iterator();
    JSONArray array = new JSONArray();
    while (cursor.hasNext()) {
        Document document = cursor.next();
        reArrangeDocument(document);
        if (withinDateRange(document.getString("Publication Date"), start, end)
                && creatorMatch(document.get("Creator"), creatorRegex)) {
            array.put(JSON.parse(document.toJson()));
        }
    }
    return Response.ok(array.toString()).cacheControl(control).build();
}