Example usage for org.json JSONObject opt

List of usage examples for org.json JSONObject opt

Introduction

In this page you can find the example usage for org.json JSONObject opt.

Prototype

public Object opt(String key) 

Source Link

Document

Get an optional value associated with a key.

Usage

From source file:org.nuclearbunny.icybee.net.impl.BitlyImpl.java

public String shrinkURL(String url) throws IOException {
    /**/* ww w .  j  a v a  2 s  . co m*/
     * bit.ly provides an elegant REST API that returns results in either JSON
     * or XML format. See http://bitly.com/app/developers for more information.
     */
    StringBuilder buffer = new StringBuilder(BITLY_URL);
    buffer.append("?version=2.0.1").append("&format=json").append("&login=").append(BITLY_API_LOGIN)
            .append("&apiKey=").append(BITLY_API_KEY).append("&longUrl=")
            .append(URLEncoder.encode(url, "UTF-8"));

    URL bitlyURL = new URL(buffer.toString());
    URLConnection connection = bitlyURL.openConnection();

    String newURL = url;

    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        JSONObject jsonObject = new JSONObject(new JSONTokener(in));
        if ("OK".equals(jsonObject.opt("statusCode"))) {
            JSONObject results = (JSONObject) jsonObject.get("results");
            results = (JSONObject) results.get(url);
            newURL = results.get("shortUrl").toString();
        }
    } catch (JSONException e) {
        e.printStackTrace(System.err);
        throw new IOException(e.getMessage());
    }

    return newURL;
}

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

private static void processGraphObjectProperty(String key, Object value, KeyValueSerializer serializer,
        boolean passByValue) throws IOException {
    Class<?> valueClass = value.getClass();
    if (GraphObject.class.isAssignableFrom(valueClass)) {
        value = ((GraphObject) value).getInnerJSONObject();
        valueClass = value.getClass();//from   w  ww .  j  a  va2 s .  c om
    } else if (GraphObjectList.class.isAssignableFrom(valueClass)) {
        value = ((GraphObjectList<?>) value).getInnerJSONArray();
        valueClass = value.getClass();
    }

    if (JSONObject.class.isAssignableFrom(valueClass)) {
        JSONObject jsonObject = (JSONObject) value;
        if (passByValue) {
            // We need to pass all properties of this object in key[propertyName] format.
            @SuppressWarnings("unchecked")
            Iterator<String> keys = jsonObject.keys();
            while (keys.hasNext()) {
                String propertyName = keys.next();
                String subKey = String.format("%s[%s]", key, propertyName);
                processGraphObjectProperty(subKey, jsonObject.opt(propertyName), serializer, passByValue);
            }
        } else {
            // Normal case is passing objects by reference, so just pass the ID or URL, if any, as the value
            // for "key"
            if (jsonObject.has("id")) {
                processGraphObjectProperty(key, jsonObject.optString("id"), serializer, passByValue);
            } else if (jsonObject.has("url")) {
                processGraphObjectProperty(key, jsonObject.optString("url"), serializer, passByValue);
            }
        }
    } else if (JSONArray.class.isAssignableFrom(valueClass)) {
        JSONArray jsonArray = (JSONArray) value;
        int length = jsonArray.length();
        for (int i = 0; i < length; ++i) {
            String subKey = String.format("%s[%d]", key, i);
            processGraphObjectProperty(subKey, jsonArray.opt(i), serializer, passByValue);
        }
    } else if (String.class.isAssignableFrom(valueClass) || Number.class.isAssignableFrom(valueClass)
            || Boolean.class.isAssignableFrom(valueClass)) {
        serializer.writeString(key, value.toString());
    } else if (Date.class.isAssignableFrom(valueClass)) {
        Date date = (Date) value;
        // The "Events Timezone" platform migration affects what date/time formats Facebook accepts and returns.
        // Apps created after 8/1/12 (or apps that have explicitly enabled the migration) should send/receive
        // dates in ISO-8601 format. Pre-migration apps can send as Unix timestamps. Since the future is ISO-8601,
        // that is what we support here. Apps that need pre-migration behavior can explicitly send these as
        // integer timestamps rather than Dates.
        final SimpleDateFormat iso8601DateFormat = new SimpleDateFormat(ISO_8601_FORMAT_STRING, Locale.US);
        serializer.writeString(key, iso8601DateFormat.format(date));
    }
}

From source file:de.grobox.blitzmail.MainActivity.java

private void sendNow() {
    JSONObject mails = MailStorage.getMails(this);

    Iterator<?> i = mails.keys();

    while (i.hasNext()) {
        String mail = mails.opt((String) i.next()).toString();

        Intent intent = new Intent(this, SendActivity.class);
        intent.setAction("BlitzMailReSend");
        intent.putExtra("mail", mail);
        startActivity(intent);/*w  w  w .  j a va 2s.  c o  m*/
    }

    ((PreferenceCategory) findPreference("pref_sending")).removePreference(findPreference("pref_send_now"));
}

From source file:com.trk.aboutme.facebook.model.JsonUtil.java

static boolean jsonObjectContainsValue(JSONObject jsonObject, Object value) {
    @SuppressWarnings("unchecked")
    Iterator<String> keys = (Iterator<String>) jsonObject.keys();
    while (keys.hasNext()) {
        Object thisValue = jsonObject.opt(keys.next());
        if (thisValue != null && thisValue.equals(value)) {
            return true;
        }//w  w w . j  ava2 s . c o m
    }
    return false;
}

From source file:com.trk.aboutme.facebook.model.JsonUtil.java

static Set<Map.Entry<String, Object>> jsonObjectEntrySet(JSONObject jsonObject) {
    HashSet<Map.Entry<String, Object>> result = new HashSet<Map.Entry<String, Object>>();

    @SuppressWarnings("unchecked")
    Iterator<String> keys = (Iterator<String>) jsonObject.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        Object value = jsonObject.opt(key);
        result.add(new JSONObjectEntry(key, value));
    }/*from w w  w. ja  va2s .  co m*/

    return result;
}

From source file:com.trk.aboutme.facebook.model.JsonUtil.java

static Collection<Object> jsonObjectValues(JSONObject jsonObject) {
    ArrayList<Object> result = new ArrayList<Object>();

    @SuppressWarnings("unchecked")
    Iterator<String> keys = (Iterator<String>) jsonObject.keys();
    while (keys.hasNext()) {
        result.add(jsonObject.opt(keys.next()));
    }//from  w  w  w .  j a v a2  s  .  com

    return result;
}

From source file:fr.arnaudguyon.xmltojsonlib.XmlToJson.java

private void format(JSONObject jsonObject, StringBuilder builder, String indent) {
    Iterator<String> keys = jsonObject.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        builder.append(indent);/*  w  ww  . j  av a 2 s.  co  m*/
        builder.append(mIndentationPattern);
        builder.append("\"");
        builder.append(key);
        builder.append("\": ");
        Object value = jsonObject.opt(key);
        if (value instanceof JSONObject) {
            JSONObject child = (JSONObject) value;
            builder.append(indent);
            builder.append("{\n");
            format(child, builder, indent + mIndentationPattern);
            builder.append(indent);
            builder.append(mIndentationPattern);
            builder.append("}");
        } else if (value instanceof JSONArray) {
            JSONArray array = (JSONArray) value;
            formatArray(array, builder, indent + mIndentationPattern);
        } else {
            formatValue(value, builder);
        }
        if (keys.hasNext()) {
            builder.append(",\n");
        } else {
            builder.append("\n");
        }
    }
}

From source file:com.tesobe.obp.transport.spi.ConnectorNov2016Test.java

@Test
public void describe() throws Exception {
    String json = connector.describe();
    JSONObject description = new JSONObject(json);

    assertThat(description.opt("error"), nullValue());

    System.out.println(description.toString(2));
}

From source file:com.eutectoid.dosomething.picker.GraphObjectAdapter.java

protected Uri getPictureUriOfGraphObject(JSONObject graphObject) {
    String uri = null;//w  w w .java  2s .co  m
    Object o = graphObject.opt(PICTURE);
    if (o instanceof String) {
        uri = (String) o;
    } else if (o instanceof JSONObject) {
        JSONObject data = ((JSONObject) o).optJSONObject("data");
        uri = data != null ? data.optString("url") : null;
    }

    if (uri != null) {
        return Uri.parse(uri);
    }
    return null;
}

From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java

private static void addGroupToXml(Element root, Group group, JSONObject in, String section, String permlevel)
        throws JSONException, UnderlyingStorageException {
    if (group.isServicesReadOnly()) {
        // Omit fields that are read-only in the services layer.
        log.debug("Omitting services-readonly group: " + group.getID());
        return;//from  w w  w .j ava 2  s  .  co m
    }

    Element element = root;

    if (group.hasServicesParent()) {
        for (String path : group.getServicesParent()) {
            if (path != null) {
                element = element.addElement(path);
            }
        }
    }

    Object value = null;
    value = in.opt(group.getID());

    if (value == null || ((value instanceof String) && StringUtils.isBlank((String) value)))
        return;
    if (value instanceof String) { // And sometimes the services ahead of the UI
        JSONObject next = new JSONObject();
        next.put(group.getID(), value);
        value = next;
    }
    if (!(value instanceof JSONObject))
        throw new UnderlyingStorageException(
                "Bad JSON in repeated field: must be string or object for group field not an array - that would a repeat field");
    JSONObject object = (JSONObject) value;

    Element groupelement = element;

    groupelement = element.addElement(group.getServicesTag());
    Object one_value = object;
    if (one_value == null || ((one_value instanceof String) && StringUtils.isBlank((String) one_value))) { //do nothing 

    } else if (one_value instanceof String) {
        // Assume it's just the first entry (useful if there's only one)
        FieldSet[] fs = group.getChildren(permlevel);
        if (fs.length < 1) { //do nothing 

        } else {
            JSONObject d1 = new JSONObject();
            d1.put(fs[0].getID(), one_value);
            addFieldSetToXml(groupelement, fs[0], d1, section, permlevel);
        }
    } else if (one_value instanceof JSONObject) {
        List<FieldSet> children = getChildrenWithGroupFields(group, permlevel);
        for (FieldSet fs : children)
            addFieldSetToXml(groupelement, fs, (JSONObject) one_value, section, permlevel);
    }
    element = groupelement;
}