Example usage for org.json JSONArray put

List of usage examples for org.json JSONArray put

Introduction

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

Prototype

public JSONArray put(Object value) 

Source Link

Document

Append an object value.

Usage

From source file:org.servalproject.maps.bridge.json.FistJsonMaker.java

/**
 * take a table row as represented by a ContentValues object and return a JSON encoded string
 * @param values a ContentValues object representing a row in the database
 * @return a JSON encoded string of the data
 * @throws JSONException if the encode to JSON fails
 *//* ww w .ja v  a 2  s  . co m*/
public static String makePoiJson(ContentValues values) throws JSONException {

    // construct the JSON objects / arrays

    //add boilerplate to the container
    JSONObject mContainer = new JSONObject();
    mContainer.put("Version", "1.0");

    // build the event object
    JSONObject mEvent = new JSONObject();
    mEvent.put("imei", sImei);
    mEvent.put("messageCode", sMessageCode);
    mEvent.put("freeText", values.get(PointsOfInterestContract.Table.TITLE) + "<br/>"
            + values.get(PointsOfInterestContract.Table.DESCRIPTION));
    mEvent.put("timeStamp", values.get(PointsOfInterestContract.Table.TIMESTAMP));

    // build the addresses array
    JSONArray mAddresses = new JSONArray();

    for (String mAddress : sAddresses) {
        mAddresses.put(new JSONObject().put("address", mAddress));
    }
    ;

    mEvent.put("addresses", mAddresses);

    // build the point object
    JSONObject mPoint = new JSONObject();
    mPoint.put("latitude", values.get(PointsOfInterestContract.Table.LATITUDE));
    mPoint.put("longitude", values.get(PointsOfInterestContract.Table.LONGITUDE));
    mPoint.put("altitude", values.get(PointsOfInterestContract.Table.ALTITUDE));
    mPoint.put("gpsfix", values.get(PointsOfInterestContract.Table.ACCURACY));
    mPoint.put("course", sMissingPointValues);
    mPoint.put("speed", sMissingPointValues);

    // add the point object
    mEvent.put("point", mPoint);

    // build the status object
    JSONObject mStatus = new JSONObject();
    mStatus.put("autonomous", sMissingStatusValues);
    mStatus.put("lowBattery", sMissingStatusValues);
    mStatus.put("intervalChange", sMissingStatusValues);

    mEvent.put("status", mStatus);

    // build the events array
    JSONArray mEvents = new JSONArray();
    mEvents.put(mEvent);

    // finalise the object
    mContainer.put("Events", mEvents);

    return mContainer.toString();
}

From source file:com.uzmap.pkg.uzmodules.uzBMap.callback.DriveRoutePlanCallBack.java

private void putSuggest(JSONObject err, List<PoiInfo> nodes, String name) {
    JSONArray suggesArray = new JSONArray();
    JSONObject suggestNode = null;//from   w w w .  j  av a 2s  .com
    try {
        if (nodes != null && nodes.size() > 0) {
            for (PoiInfo poiInfo : nodes) {
                suggestNode = new JSONObject();
                LatLng latLng = poiInfo.location;
                suggestNode.put("name", poiInfo.name);
                suggestNode.put("city", poiInfo.city);
                suggestNode.put("lat", latLng.latitude);
                suggestNode.put("lon", latLng.longitude);
                suggesArray.put(suggestNode);
            }
            err.put(name, suggesArray);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.uzmap.pkg.uzmodules.uzBMap.callback.DriveRoutePlanCallBack.java

private void putSteps(DrivingRouteLine plan, JSONObject nodeJson, JSONArray array) {
    List<DrivingStep> steps = plan.getAllStep();
    for (DrivingStep step : steps) {
        nodeJson = new JSONObject();
        LatLng nodeLocation = step.getEntrance().getLocation();
        try {/*from  www  . j  a v a  2  s. co  m*/
            nodeJson.put("lon", nodeLocation.longitude);
            nodeJson.put("lat", nodeLocation.latitude);
            nodeJson.put("degree", step.getDirection());
            nodeJson.put("description", step.getInstructions());
            array.put(nodeJson);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.uzmap.pkg.uzmodules.uzBMap.callback.DriveRoutePlanCallBack.java

private void initCallBackJson(JSONArray plansJson, JSONObject planJson, JSONObject startJson,
        JSONObject endJson, JSONArray array) {
    try {//from  w  ww.j  a  v  a2 s  .co m
        planJson.put("start", startJson);
        planJson.put("end", endJson);
        planJson.put("nodes", array);
        plansJson.put(planJson);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.google.android.apps.paco.ExploreDataActivity.java

private JSONArray convertExperimentDataToJsonArray(Experiment experiment) {
    final JSONArray experimentData = new JSONArray();
    for (Event event : experiment.getEvents()) {
        try {/*from   ww w.  j a va  2  s  . c o m*/
            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());
                responseJson.put("inputName", input.getName());
                responseJson.put("responseType", input.getResponseType());
                responseJson.put("prompt",
                        experiment.getFeedback().get(0).getTextOfInputForOutput(experiment, response));
                responseJson.put("answer", response.getDisplayOfAnswer(input));
                responseJson.put("answerOrder", 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.
        }
    }
    return experimentData;
}

From source file:com.google.android.apps.paco.ExploreDataActivity.java

/**
 * @param inputId//w w  w  . ja  va 2  s . c o m
 * @param localExperiment
 * @return
 */
private JSONArray getResultsForInputAsJsonString(long inputId, Experiment localExperiment) {
    JSONArray results = new JSONArray();
    for (Event event : localExperiment.getEvents()) {
        JSONArray eventJson = new JSONArray();
        DateTime responseTime = event.getResponseTime();
        if (responseTime == null) {
            continue; // missed signal;
        }
        eventJson.put(responseTime.getMillis());

        // in this case we are looking for one input from the responses that we are charting.
        for (Output response : event.getResponses()) {
            if (response.getInputServerId() == inputId) {
                Input inputById = localExperiment.getInputById(inputId);
                if (!inputById.isInvisible() && inputById.isNumeric()) {
                    eventJson.put(response.getDisplayOfAnswer(inputById));
                    results.put(eventJson);
                    continue;
                }
            }
        }

    }
    return results;
}

From source file:org.apache.cordova.contacts.ContactAccessorSdk5.java

/**
 * Creates an array of contacts from the cursor you pass in
 *
 * @param limit        max number of contacts for the array
 * @param populate     whether or not you should populate a certain value
 * @param c            the cursor/*from  www.j  ava2 s  .  c  o  m*/
 * @return             a JSONArray of contacts
 */
private JSONArray populateContactArray(int limit, HashMap<String, Boolean> populate, Cursor c) {

    String contactId = "";
    String rawId = "";
    String oldContactId = "";
    boolean newContact = true;
    String mimetype = "";

    JSONArray contacts = new JSONArray();
    JSONObject contact = new JSONObject();
    JSONArray organizations = new JSONArray();
    JSONArray addresses = new JSONArray();
    JSONArray phones = new JSONArray();
    JSONArray emails = new JSONArray();
    JSONArray ims = new JSONArray();
    JSONArray websites = new JSONArray();
    JSONArray photos = new JSONArray();

    // Column indices
    int colContactId = c.getColumnIndex(ContactsContract.Data.CONTACT_ID);
    int colRawContactId = c.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID);
    int colMimetype = c.getColumnIndex(ContactsContract.Data.MIMETYPE);
    int colDisplayName = c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
    int colNote = c.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE);
    int colNickname = c.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME);
    int colBirthday = c.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
    int colEventType = c.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE);

    if (c.getCount() > 0) {
        while (c.moveToNext() && (contacts.length() <= (limit - 1))) {
            try {
                contactId = c.getString(colContactId);
                rawId = c.getString(colRawContactId);

                // If we are in the first row set the oldContactId
                if (c.getPosition() == 0) {
                    oldContactId = contactId;
                }

                // When the contact ID changes we need to push the Contact object
                // to the array of contacts and create new objects.
                if (!oldContactId.equals(contactId)) {
                    // Populate the Contact object with it's arrays
                    // and push the contact into the contacts array
                    contacts.put(populateContact(contact, organizations, addresses, phones, emails, ims,
                            websites, photos));

                    // Clean up the objects
                    contact = new JSONObject();
                    organizations = new JSONArray();
                    addresses = new JSONArray();
                    phones = new JSONArray();
                    emails = new JSONArray();
                    ims = new JSONArray();
                    websites = new JSONArray();
                    photos = new JSONArray();

                    // Set newContact to true as we are starting to populate a new contact
                    newContact = true;
                }

                // When we detect a new contact set the ID and display name.
                // These fields are available in every row in the result set returned.
                if (newContact) {
                    newContact = false;
                    contact.put("id", contactId);
                    contact.put("rawId", rawId);
                }

                // Grab the mimetype of the current row as it will be used in a lot of comparisons
                mimetype = c.getString(colMimetype);

                if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                        && isRequired("name", populate)) {
                    contact.put("displayName", c.getString(colDisplayName));
                }

                if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                        && isRequired("name", populate)) {
                    contact.put("name", nameQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                        && isRequired("phoneNumbers", populate)) {
                    phones.put(phoneQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
                        && isRequired("emails", populate)) {
                    emails.put(emailQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
                        && isRequired("addresses", populate)) {
                    addresses.put(addressQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
                        && isRequired("organizations", populate)) {
                    organizations.put(organizationQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
                        && isRequired("ims", populate)) {
                    ims.put(imQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
                        && isRequired("note", populate)) {
                    contact.put("note", c.getString(colNote));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
                        && isRequired("nickname", populate)) {
                    contact.put("nickname", c.getString(colNickname));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
                        && isRequired("urls", populate)) {
                    websites.put(websiteQuery(c));
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)) {
                    if (isRequired("birthday", populate)
                            && ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY == c.getInt(colEventType)) {
                        contact.put("birthday", c.getString(colBirthday));
                    }
                } else if (mimetype.equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
                        && isRequired("photos", populate)) {
                    JSONObject photo = photoQuery(c, contactId);
                    if (photo != null) {
                        photos.put(photo);
                    }
                }
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
            }

            // Set the old contact ID
            oldContactId = contactId;

        }

        // Push the last contact into the contacts array
        if (contacts.length() < limit) {
            contacts.put(
                    populateContact(contact, organizations, addresses, phones, emails, ims, websites, photos));
        }
    }
    c.close();
    return contacts;
}

From source file:org.ohmage.request.audit.AuditReadRequest.java

/**
 * Replies to the request./*from   w  w  w . j a  va2 s  . c  o m*/
 */
@Override
public void respond(HttpServletRequest httpRequest, HttpServletResponse httpResponse) {
    // Build the result object.
    JSONArray resultJson = new JSONArray();
    for (Audit result : results) {
        resultJson.put(result.toJson());
    }

    super.respond(httpRequest, httpResponse, RESULT_KEY, resultJson);
}

From source file:app.sunstreak.yourpisd.net.Parser.java

public static JSONArray detailedReport(String html) throws JSONException {
    Element doc = Jsoup.parse(html);
    //      System.out.println(html);
    Element assignments = doc.getElementsByAttributeValue("id", "Assignments").get(0);
    Elements tableRows = assignments.getElementsByTag("tbody").get(0).getElementsByTag("tr");

    JSONArray grades = new JSONArray();

    for (Element tr : tableRows) {
        JSONObject assignment = new JSONObject();

        Elements columns = tr.getElementsByTag("td");

        for (int i = 0; i < columns.size(); i++) {
            String value = columns.get(i).text();
            // do not store empty values!
            if (value.equals(""))
                continue;
            // first try to cast as int.
            try {
                assignment.putOpt(assignmentTableHeader(i), Integer.parseInt(value));
                // if not int, try double
            } catch (NumberFormatException e) {
                try {
                    assignment.putOpt(assignmentTableHeader(i), Double.parseDouble(value));
                    // if not double, use string
                } catch (NumberFormatException f) {
                    assignment.putOpt(assignmentTableHeader(i), value);
                }/*from   w  w  w. j  a  va  2s. c o  m*/
            }
        }

        String assignmentDetailLink = tr.getElementsByTag("a").get(0).attr("href");
        Matcher matcher = Pattern.compile(".+" + "assignmentId=(\\d+)" + "&H=S" + "&GradebookId=(\\d+)"
                + "&TermId=\\d+" + "&StudentId=\\d+&").matcher(assignmentDetailLink);
        matcher.find();
        int assignmentId = Integer.parseInt(matcher.group(1));
        int gradebookId = Integer.parseInt(matcher.group(2));
        assignment.put("assignmentId", assignmentId);
        assignment.put("gradebookId", gradebookId);
        grades.put(assignment);
    }
    //      System.out.println((grades));
    return grades;
}

From source file:app.sunstreak.yourpisd.net.Parser.java

public static Object[] termCategoryGrades(String html) throws JSONException {
    JSONArray termCategoryGrades = new JSONArray();

    Element doc = Jsoup.parse(html);
    Element categoryTable = doc.getElementById("Category");
    Elements rows = categoryTable.getElementsByTag("tbody").get(0).getElementsByTag("tr");

    for (Element row : rows) {
        JSONObject category = new JSONObject();
        Elements columns = row.getElementsByTag("td");
        for (int i = 0; i < columns.size(); i++) {

            String value = columns.get(i).text();
            // do not store empty values!
            if (value.equals(""))
                continue;
            // first try to cast as int.
            try {
                category.putOpt(categoryTableHeader(i), Integer.parseInt(value));
                // if not int, try double
            } catch (NumberFormatException e) {
                try {
                    category.putOpt(categoryTableHeader(i), Double.parseDouble(value));
                    // if not double, use string
                } catch (NumberFormatException f) {
                    category.putOpt(categoryTableHeader(i), value);
                }//from w w w.  ja va  2s.  co  m
            }
        }
        termCategoryGrades.put(category);

    }

    // The average for the six weeks is 
    int average = -1;
    try {
        Element finalGrade = doc.getElementById("finalGrade");
        average = Integer.parseInt(finalGrade.getElementsByTag("td").get(3).text());
    } catch (NullPointerException e) {
        // Let average be -1
    }

    return new Object[] { termCategoryGrades, average };
}