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:test.Testing.java

public static void main(String[] args) throws Exception {
    ////////////////////////////////////////////////////////////////////////////////////////////
    // Setup//from   www.  j a va 2 s  .  c o  m
    ////////////////////////////////////////////////////////////////////////////////////////////
    String key = "CHANGEME: YOUR_API_KEY";
    String secret = "CHANGEME: YOUR_API_SECRET";
    String version = "preview1";
    String practiceid = "000000";

    APIConnection api = new APIConnection(version, key, secret, practiceid);
    api.authenticate();

    // If you want to set the practice ID after construction, this is how.
    // api.setPracticeID("000000");

    ////////////////////////////////////////////////////////////////////////////////////////////
    // GET without parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    JSONArray customfields = (JSONArray) api.GET("/customfields");
    System.out.println("Custom fields:");
    for (int i = 0; i < customfields.length(); i++) {
        System.out.println("\t" + customfields.getJSONObject(i).get("name"));
    }

    ////////////////////////////////////////////////////////////////////////////////////////////
    // GET with parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
    Calendar today = Calendar.getInstance();
    Calendar nextyear = Calendar.getInstance();
    nextyear.roll(Calendar.YEAR, 1);

    Map<String, String> search = new HashMap<String, String>();
    search.put("departmentid", "82");
    search.put("startdate", format.format(today.getTime()));
    search.put("enddate", format.format(nextyear.getTime()));
    search.put("appointmenttypeid", "2");
    search.put("limit", "1");

    JSONObject open_appts = (JSONObject) api.GET("/appointments/open", search);
    System.out.println(open_appts.toString());
    JSONObject appt = open_appts.getJSONArray("appointments").getJSONObject(0);
    System.out.println("Open appointment:");
    System.out.println(appt.toString());

    // add keys to make appt usable for scheduling
    appt.put("appointmenttime", appt.get("starttime"));
    appt.put("appointmentdate", appt.get("date"));

    ////////////////////////////////////////////////////////////////////////////////////////////
    // POST with parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    Map<String, String> patient_info = new HashMap<String, String>();
    patient_info.put("lastname", "Foo");
    patient_info.put("firstname", "Jason");
    patient_info.put("address1", "123 Any Street");
    patient_info.put("city", "Cambridge");
    patient_info.put("countrycode3166", "US");
    patient_info.put("departmentid", "1");
    patient_info.put("dob", "6/18/1987");
    patient_info.put("language6392code", "declined");
    patient_info.put("maritalstatus", "S");
    patient_info.put("race", "declined");
    patient_info.put("sex", "M");
    patient_info.put("ssn", "*****1234");
    patient_info.put("zip", "02139");

    JSONArray new_patient = (JSONArray) api.POST("/patients", patient_info);
    String new_patient_id = new_patient.getJSONObject(0).getString("patientid");
    System.out.println("New patient id:");
    System.out.println(new_patient_id);

    ////////////////////////////////////////////////////////////////////////////////////////////
    // PUT with parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    Map<String, String> appointment_info = new HashMap<String, String>();
    appointment_info.put("appointmenttypeid", "82");
    appointment_info.put("departmentid", "1");
    appointment_info.put("patientid", new_patient_id);

    JSONArray booked = (JSONArray) api.PUT("/appointments/" + appt.getString("appointmentid"),
            appointment_info);
    System.out.println("Booked:");
    System.out.println(booked.toString());

    ////////////////////////////////////////////////////////////////////////////////////////////
    // POST without parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    JSONObject checked_in = (JSONObject) api
            .POST("/appointments/" + appt.getString("appointmentid") + "/checkin");
    System.out.println("Check-in:");
    System.out.println(checked_in.toString());

    ////////////////////////////////////////////////////////////////////////////////////////////
    // DELETE with parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    Map<String, String> delete_params = new HashMap<String, String>();
    delete_params.put("departmentid", "1");
    JSONObject chart_alert = (JSONObject) api.DELETE("/patients/" + new_patient_id + "/chartalert",
            delete_params);
    System.out.println("Removed chart alert:");
    System.out.println(chart_alert.toString());

    ////////////////////////////////////////////////////////////////////////////////////////////
    // DELETE without parameters
    ////////////////////////////////////////////////////////////////////////////////////////////
    JSONObject photo = (JSONObject) api.DELETE("/patients/" + new_patient_id + "/photo");
    System.out.println("Removed photo:");
    System.out.println(photo.toString());

    ////////////////////////////////////////////////////////////////////////////////////////////
    // There are no PUTs without parameters
    ////////////////////////////////////////////////////////////////////////////////////////////

    ////////////////////////////////////////////////////////////////////////////////////////////
    // Error conditions
    ////////////////////////////////////////////////////////////////////////////////////////////
    JSONObject bad_path = (JSONObject) api.GET("/nothing/at/this/path");
    System.out.println("GET /nothing/at/this/path:");
    System.out.println(bad_path.toString());
    JSONObject missing_parameters = (JSONObject) api.GET("/appointments/open");
    System.out.println("Missing parameters:");
    System.out.println(missing_parameters.toString());

    ////////////////////////////////////////////////////////////////////////////////////////////
    // Testing token refresh
    //
    // NOTE: this test takes an hour, so it's disabled by default. Change false to true to run.
    ////////////////////////////////////////////////////////////////////////////////////////////
    if (false) {
        String old_token = api.getToken();
        System.out.println("Old token: " + old_token);

        JSONObject before_refresh = (JSONObject) api.GET("/departments");

        // Wait 3600 seconds = 1 hour for token to expire.
        try {
            Thread.sleep(3600 * 1000);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        JSONObject after_refresh = (JSONObject) api.GET("/departments");

        System.out.println("New token: " + api.getToken());
    }
}

From source file:com.andybotting.tramhunter.objects.FavouriteList.java

/**
 * Convert an old favourites string to the new JSON format
 * @param favouriteString/* w  w  w  . jav a 2s  . co  m*/
 * @return JSONArray
 */
private String convertOldFavourites(String favouriteString) {

    try {
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject;
        int tramTrackerId;

        StringTokenizer tokenizer = new StringTokenizer(favouriteString, ",");
        while (tokenizer.hasMoreTokens()) {
            tramTrackerId = Integer.parseInt(tokenizer.nextToken());
            jsonObject = new JSONObject();
            jsonObject.put("stop", tramTrackerId);
            jsonArray.put(jsonObject);
        }
        return jsonArray.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return "";
}

From source file:com.keylesspalace.tusky.util.NotificationMaker.java

public static void make(final Context context, final int notifyId, Notification body) {
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    final SharedPreferences notificationPreferences = context.getSharedPreferences("Notifications",
            Context.MODE_PRIVATE);

    if (!filterNotification(preferences, body)) {
        return;//from   w  w w .  ja v  a 2  s . c o  m
    }

    String rawCurrentNotifications = notificationPreferences.getString("current", "[]");
    JSONArray currentNotifications;

    try {
        currentNotifications = new JSONArray(rawCurrentNotifications);
    } catch (JSONException e) {
        currentNotifications = new JSONArray();
    }

    boolean alreadyContains = false;

    for (int i = 0; i < currentNotifications.length(); i++) {
        try {
            if (currentNotifications.getString(i).equals(body.account.getDisplayName())) {
                alreadyContains = true;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    if (!alreadyContains) {
        currentNotifications.put(body.account.getDisplayName());
    }

    notificationPreferences.edit().putString("current", currentNotifications.toString()).commit();

    Intent resultIntent = new Intent(context, MainActivity.class);
    resultIntent.putExtra("tab_position", 1);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent deleteIntent = new Intent(context, NotificationClearBroadcastReceiver.class);
    PendingIntent deletePendingIntent = PendingIntent.getBroadcast(context, 0, deleteIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_notify).setContentIntent(resultPendingIntent)
            .setDeleteIntent(deletePendingIntent).setDefaults(0); // So it doesn't ring twice, notify only in Target callback

    if (currentNotifications.length() == 1) {
        builder.setContentTitle(titleForType(context, body))
                .setContentText(truncateWithEllipses(bodyForType(body), 40));

        Target mTarget = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                builder.setLargeIcon(bitmap);

                setupPreferences(preferences, builder);

                ((NotificationManager) (context.getSystemService(Context.NOTIFICATION_SERVICE)))
                        .notify(notifyId, builder.build());
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
            }
        };

        Picasso.with(context).load(body.account.avatar).placeholder(R.drawable.avatar_default)
                .transform(new RoundedTransformation(7, 0)).into(mTarget);
    } else {
        setupPreferences(preferences, builder);
        try {
            builder.setContentTitle(String.format(context.getString(R.string.notification_title_summary),
                    currentNotifications.length()))
                    .setContentText(truncateWithEllipses(joinNames(context, currentNotifications), 40));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setVisibility(android.app.Notification.VISIBILITY_PRIVATE);
        builder.setCategory(android.app.Notification.CATEGORY_SOCIAL);
    }

    ((NotificationManager) (context.getSystemService(Context.NOTIFICATION_SERVICE))).notify(notifyId,
            builder.build());
}

From source file:com.esri.cordova.geolocation.AdvancedGeolocation.java

private void parseArgs(JSONArray args) {
    Log.d(TAG, "Execute args: " + args.toString());
    if (args.length() > 0) {
        try {//from  www .j a v  a2 s  .co m
            final JSONObject obj = args.getJSONObject(0);
            _minTime = obj.getLong("minTime");
            _minDistance = obj.getLong("minDistance");
            _noWarn = obj.getBoolean("noWarn");
            _providers = obj.getString("providers");
            _useCache = obj.getBoolean("useCache");
            _returnSatelliteData = obj.getBoolean("satelliteData");
            _buffer = obj.getBoolean("buffer");
            _signalStrength = obj.getBoolean("signalStrength");
            _bufferSize = obj.getInt("bufferSize");

        } catch (Exception exc) {
            Log.d(TAG, ErrorMessages.INCORRECT_CONFIG_ARGS + ", " + exc.getMessage());
            sendCallback(PluginResult.Status.ERROR,
                    ErrorMessages.INCORRECT_CONFIG_ARGS + ", " + exc.getMessage());
        }
    }
}

From source file:com.trk.aboutme.facebook.Request.java

private static void serializeRequestsAsJSON(Serializer serializer, Collection<Request> requests,
        Bundle attachments) throws JSONException, IOException {
    JSONArray batch = new JSONArray();
    for (Request request : requests) {
        request.serializeToBatch(batch, attachments);
    }/*  ww w.j  a  va 2  s.  c o  m*/

    String batchAsString = batch.toString();
    serializer.writeString(BATCH_PARAM, batchAsString);
}

From source file:com.neka.cordova.inappbrowser.InAppBrowser.java

/**
 * Inject an object (script or style) into the InAppBrowser WebView.
 *
 * This is a helper method for the inject{Script|Style}{Code|File} API calls, which
 * provides a consistent method for injecting JavaScript code into the document.
 *
 * If a wrapper string is supplied, then the source string will be JSON-encoded (adding
 * quotes) and wrapped using string formatting. (The wrapper string should have a single
 * '%s' marker)/*from  w ww .  j  a  v  a 2  s .c o m*/
 *
 * @param source      The source object (filename or script/style text) to inject into
 *                    the document.
 * @param jsWrapper   A JavaScript string to wrap the source string in, so that the object
 *                    is properly injected, or null if the source string is JavaScript text
 *                    which should be executed directly.
 */
private void injectDeferredObject(String source, String jsWrapper) {
    String scriptToInject;
    if (jsWrapper != null) {
        org.json.JSONArray jsonEsc = new org.json.JSONArray();
        jsonEsc.put(source);
        String jsonRepr = jsonEsc.toString();
        String jsonSourceString = jsonRepr.substring(1, jsonRepr.length() - 1);
        scriptToInject = String.format(jsWrapper, jsonSourceString);
    } else {
        scriptToInject = source;
    }
    final String finalScriptToInject = scriptToInject;
    this.cordova.getActivity().runOnUiThread(new Runnable() {
        @SuppressLint("NewApi")
        @Override
        public void run() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                // This action will have the side-effect of blurring the currently focused element
                inAppWebView.loadUrl("javascript:" + finalScriptToInject);
            } else {
                inAppWebView.evaluateJavascript(finalScriptToInject, null);
            }
        }
    });
}

From source file:ecjtu.net.demon.utils.ACache.java

/**
 * ? JSONArray?  /*from  w w  w.ja  v  a 2 s  . c  o m*/
 * 
 * @param key
 *            ?key
 * @param value
 *            ?JSONArray?
 */
public void put(String key, JSONArray value) {
    put(key, value.toString());
}

From source file:ecjtu.net.demon.utils.ACache.java

/**
 * ? JSONArray?  //from   w w w. j  a  va 2s  .  co m
 * 
 * @param key
 *            ?key
 * @param value
 *            ?JSONArray?
 * @param saveTime
 *            ???
 */
public void put(String key, JSONArray value, int saveTime) {
    put(key, value.toString(), saveTime);
}

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

@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)//ww  w.j a va  2s  . c  om
public Response getROsList(@QueryParam("Purpose") final String purpose) {
    FindIterable<Document> iter;
    if (purpose != null && purpose.equals("Production")) {
        iter = publicationsCollection.find(Filters.ne("Preferences.Purpose", "Testing-Only"));
    } else if (purpose != null && purpose.equals("Testing-Only")) {
        iter = publicationsCollection.find(Filters.eq("Preferences.Purpose", purpose));
    } else if (purpose != null) {
        return Response.status(ClientResponse.Status.BAD_REQUEST)
                .entity(new JSONObject()
                        .put("Error", "'" + purpose + "' is not an acceptable value for 'Purpose'").toString())
                .build();
    } else {
        iter = publicationsCollection.find();
    }
    iter.projection(new Document("Status", 1).append("Repository", 1).append("Aggregation.Identifier", 1)
            .append("Aggregation.Title", 1).append("_id", 0));
    MongoCursor<Document> cursor = iter.iterator();
    JSONArray array = new JSONArray();
    while (cursor.hasNext()) {
        array.put(JSON.parse(cursor.next().toJson()));
    }
    return Response.ok(array.toString()).cacheControl(control).build();
}

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

@GET
@Path("/new/")
@Produces(MediaType.APPLICATION_JSON)/*from   ww w . java 2 s .com*/
public Response getNewROsList(@QueryParam("Purpose") final String purpose) {
    //Find ROs that have a status not from the services and don't include them :-)
    Document reporterRule = new Document("$ne", Constants.serviceName);
    Document reporter = new Document("reporter", reporterRule);
    Document elem = new Document("$elemMatch", reporter);
    Document not = new Document("$not", elem);
    Document match = new Document("Status", not);

    FindIterable<Document> iter;
    if (purpose != null && purpose.equals("Production")) {
        iter = publicationsCollection
                .find(Filters.and(match, Filters.ne("Preferences.Purpose", "Testing-Only")));
    } else if (purpose != null && purpose.equals("Testing-Only")) {
        iter = publicationsCollection.find(Filters.and(match, Filters.eq("Preferences.Purpose", purpose)));
    } else if (purpose != null) {
        return Response.status(ClientResponse.Status.BAD_REQUEST)
                .entity(new JSONObject()
                        .put("Error", "'" + purpose + "' is not an acceptable value for 'Purpose'").toString())
                .build();
    } else {
        iter = publicationsCollection.find(match);
    }
    iter.projection(new Document("Status", 1).append("Repository", 1).append("Aggregation.Identifier", 1)
            .append("Aggregation.Title", 1).append("_id", 0));
    MongoCursor<Document> cursor = iter.iterator();
    JSONArray array = new JSONArray();
    while (cursor.hasNext()) {
        array.put(JSON.parse(cursor.next().toJson()));
    }
    return Response.ok(array.toString()).cacheControl(control).build();
}