Example usage for org.json JSONArray get

List of usage examples for org.json JSONArray get

Introduction

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

Prototype

public Object get(int index) throws JSONException 

Source Link

Document

Get the object value associated with an index.

Usage

From source file:GUI.simplePanel.java

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
    try {/*from w w  w.j av  a  2 s  . c  o m*/
        String reply = util.httpRequest.sendPost("127.0.0.1", 8383, "", "/getServices");
        JSONObject obj;

        obj = new JSONObject(reply);
        JSONArray services = obj.getJSONArray("services");
        boolean found = false;
        for (int i = 0; i < services.length(); i++) {
            if (found) {
                return;
            }
            Object pref = services.getJSONObject(i).get("url");
            String url = (String) pref;
            if (url.contains("temp")) {
                // http://127.0.0.1:8181/sensor/1/temp
                String serviceHost = (url.split(":")[1].substring(2));
                int Port = Integer.parseInt((url.split(":")[2]).split("/")[0]);
                String servicePath = (url.split(":")[2].substring(url.split(":")[2].indexOf("/")));
                String serviceReply = util.httpRequest.sendPost(serviceHost, Port, "", servicePath);

                JSONObject temperature;

                obj = new JSONObject(serviceReply);
                String temp = obj.getJSONObject("sensor").getString("Temperature");
                JOptionPane.showMessageDialog(self,
                        "Temperature is " + temp.substring(0, temp.indexOf(".") + 2) + " Celsius");
                found = true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.spoiledmilk.cykelsuperstier.break_rote.BreakRouteActivity.java

private void parseStationsFromJson() {
    metroStations = new ArrayList<OverlayData>();
    sTrainStations = new ArrayList<OverlayData>();
    localTrainStations = new ArrayList<OverlayData>();
    try {//from  w w w.  ja  v  a  2  s  . co  m
        String stationsStr = Util.stringFromJsonAssets(this, "stations/stations.json");
        JSONArray stationsJson = (new JSONObject(stationsStr)).getJSONArray("stations");
        for (int i = 0; i < stationsJson.length(); i++) {
            JSONObject stationJson = (JSONObject) stationsJson.get(i);
            if (!stationJson.has("coords"))
                continue;
            String[] coords = stationJson.getString("coords").split("\\s+");
            String type = stationJson.getString("type");
            if (type.equals("service")) {
                continue;
            } else if (type.equals("metro")) {
                metroStations.add(new OverlayData(stationJson.getString("name"), stationJson.getString("line"),
                        Double.parseDouble(coords[1]), Double.parseDouble(coords[0]),
                        R.drawable.metro_logo_pin));
            } else if (type.equals("s-train")) {
                sTrainStations.add(new OverlayData(stationJson.getString("name"), stationJson.getString("line"),
                        Double.parseDouble(coords[1]), Double.parseDouble(coords[0]),
                        R.drawable.list_subway_icon));
            } else if (type.equals("local-train")) {
                localTrainStations.add(new OverlayData(stationJson.getString("name"),
                        stationJson.getString("line"), Double.parseDouble(coords[1]),
                        Double.parseDouble(coords[0]), R.drawable.list_subway_icon));
            }
        }
    } catch (Exception e) {
        LOG.e(e.getLocalizedMessage());
    }
}

From source file:test.Testing.java

public static void main(String[] args) throws Exception {
    ////////////////////////////////////////////////////////////////////////////////////////////
    // Setup//from   w  w  w .ja va  2  s  . co  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:ch.icclab.cyclops.resource.impl.ExternalAppResource.java

/**
 * Receives the JSON array, transforms it and send it to the db resource to persist it into InfluxDB
 *
 * Pseudo Code/*from  w w  w.j  a  v a  2 s. com*/
 * 1. Iterate through the JSONArray to get the JSON obj
 * 2. Iterate through the JSON Obj to get the usage details
 * 3. Build the TSDB POJO
 * 4. Pass this POJO obj to the TSDB resource for persisting it into the DB
 *
 * @param jsonArr An array containing the usage data as part of JSON Objects
 * @return String
 */
public boolean saveData(JSONArray jsonArr) {

    JSONObject jsonObj, metadata, usageData;
    String metername = null;
    String source;
    TSDBResource dbResource = new TSDBResource();
    JSONArray dataArr;
    ArrayList<Object> objArrNode;
    ArrayList<ArrayList<Object>> objArr = new ArrayList<ArrayList<Object>>();
    TSDBData dbData = new TSDBData();
    ArrayList<String> columnNameArr = new ArrayList<String>();
    columnNameArr.add("timestamp");
    columnNameArr.add("userid");
    columnNameArr.add("source");
    columnNameArr.add("usage");

    try {
        for (int i = 0; i < jsonArr.length(); i++) {
            jsonObj = (JSONObject) jsonArr.get(i);
            metadata = (JSONObject) jsonObj.get("metadata");
            source = (String) metadata.get("source");
            dataArr = (JSONArray) jsonObj.get("usage");

            for (int j = 0; j < dataArr.length(); j++) {
                objArrNode = new ArrayList<Object>();
                usageData = (JSONObject) dataArr.get(j);
                metername = (String) usageData.get("metername");
                objArrNode.add(usageData.get("timestamp"));
                objArrNode.add(usageData.get("userid"));
                objArrNode.add(source);
                objArrNode.add(usageData.get("usage"));
                objArr.add(objArrNode);
            }
            dbData.setName(metername);
            dbData.setColumns(columnNameArr);
            dbData.setPoints(objArr);

            dbResource.saveExtData(dbData);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:org.openmrs.mobile.listeners.visit.VisitTypeListener.java

@Override
public void onResponse(JSONObject response) {
    mLogger.d(response.toString());/*from  w  ww.j a v a2s.co m*/

    try {
        JSONArray visitTypesObj = response.getJSONArray("results");
        String visitTypeUUID = ((JSONObject) visitTypesObj.get(0)).getString("uuid");
        OpenMRS.getInstance().setVisitTypeUUID(visitTypeUUID);
    } catch (JSONException e) {
        mLogger.d(e.toString());
    }
}

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

@Nullable
private static String joinNames(Context context, JSONArray array) throws JSONException {
    if (array.length() > 3) {
        return String.format(context.getString(R.string.notification_summary_large), array.get(0), array.get(1),
                array.get(2), array.length() - 3);
    } else if (array.length() == 3) {
        return String.format(context.getString(R.string.notification_summary_medium), array.get(0),
                array.get(1), array.get(2));
    } else if (array.length() == 2) {
        return String.format(context.getString(R.string.notification_summary_small), array.get(0),
                array.get(1));/*from  w ww.  j a va 2 s  . c o  m*/
    }

    return null;
}

From source file:org.everit.json.schema.ObjectComparator.java

private static boolean deepEqualArrays(final JSONArray arr1, final JSONArray arr2) {
    if (arr1.length() != arr2.length()) {
        return false;
    }//  w w  w.j a  va2  s .  com
    for (int i = 0; i < arr1.length(); ++i) {
        if (!deepEquals(arr1.get(i), arr2.get(i))) {
            return false;
        }
    }
    return true;
}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesUtility.java

protected static JSONObject makeResponseJSONObject(String data) {

    JSONArray product = null;
    JSONObject ret = null;/*from w  ww  .j  a  v a2  s  .co m*/
    try {
        product = new JSONArray(data);
        ret = (JSONObject) product.get(0);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return ret;
}

From source file:to.networld.fbtosemweb.fb.FacebookAgentHandler.java

public Vector<FacebookLikesEntry> getLikesConcepts() throws IOException, JSONException {
    Vector<FacebookLikesEntry> resultEntries = new Vector<FacebookLikesEntry>();
    JSONObject likesObject = this.getContent(this.FB_LIKES_URL);
    JSONArray likesEntries = likesObject.getJSONArray("data");
    for (int count = 0; count < likesEntries.length(); count++) {
        JSONObject jsonEntry = (JSONObject) likesEntries.get(count);
        FacebookLikesEntry likesEntry = new FacebookLikesEntry(jsonEntry.getString("id"),
                jsonEntry.getString("name"), jsonEntry.getString("category"),
                jsonEntry.getString("created_time"));
        resultEntries.add(likesEntry);/*  ww  w.  j a v a 2 s. c o  m*/
    }
    return resultEntries;
}

From source file:to.networld.fbtosemweb.fb.FacebookAgentHandler.java

public Vector<FacebookFriendEntry> getFriends() throws IOException, JSONException {
    Vector<FacebookFriendEntry> resultEntries = new Vector<FacebookFriendEntry>();
    JSONObject likesObject = this.getContent(this.FB_FRIENDS_URL);
    JSONArray likesEntries = likesObject.getJSONArray("data");
    for (int count = 0; count < likesEntries.length(); count++) {
        JSONObject jsonEntry = (JSONObject) likesEntries.get(count);
        FacebookFriendEntry friendEntry = new FacebookFriendEntry(jsonEntry.getString("id"),
                jsonEntry.getString("name"));
        resultEntries.add(friendEntry);//from   ww  w .j  a  va2s  . com
    }
    return resultEntries;
}