Example usage for org.json JSONObject optString

List of usage examples for org.json JSONObject optString

Introduction

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

Prototype

public String optString(String key) 

Source Link

Document

Get an optional string associated with a key.

Usage

From source file:com.github.mhendred.face4j.model.Face.java

public Face(JSONObject jObj) throws JSONException {
    tid = jObj.getString("tid");
    label = jObj.optString("label");

    confirmed = jObj.getBoolean("confirmed");
    manual = jObj.getBoolean("manual");

    width = (float) jObj.getDouble("width");
    height = (float) jObj.getDouble("height");

    yaw = (float) jObj.getDouble("yaw");
    roll = (float) jObj.getDouble("roll");
    pitch = (float) jObj.getDouble("pitch");

    threshold = jObj.optInt("threshold");

    center = fromJson(jObj.optJSONObject("center"));

    leftEye = fromJson(jObj.optJSONObject("eye_left"));
    rightEye = fromJson(jObj.optJSONObject("eye_right"));

    leftEar = fromJson(jObj.optJSONObject("ear_left"));
    rightEar = fromJson(jObj.optJSONObject("ear_right"));

    chin = fromJson(jObj.optJSONObject("chin"));

    mouthCenter = fromJson(jObj.optJSONObject("mouth_center"));
    mouthRight = fromJson(jObj.optJSONObject("mouth_right"));
    mouthLeft = fromJson(jObj.optJSONObject("mouth_left"));

    nose = fromJson(jObj.optJSONObject("nose"));

    guesses = Guess.fromJsonArray(jObj.optJSONArray("uids"));

    // Attributes
    jObj = jObj.getJSONObject("attributes");

    if (jObj.has("smiling"))
        smiling = jObj.getJSONObject("smiling").getBoolean("value");

    if (jObj.has("glasses"))
        glasses = jObj.getJSONObject("glasses").getBoolean("value");

    if (jObj.has("gender"))
        gender = Gender.valueOf(jObj.getJSONObject("gender").getString("value"));

    if (jObj.has("mood"))
        mood = jObj.getJSONObject("mood").getString("value");

    if (jObj.has("lips"))
        lips = jObj.getJSONObject("lips").getString("value");

    if (jObj.has("age-est"))
        ageEst = jObj.getJSONObject("age-est").getInt("vaule");

    if (jObj.has("age-min"))
        ageMin = jObj.getJSONObject("age-min").getInt("vaule");

    if (jObj.has("age-max"))
        ageMax = jObj.getJSONObject("age-max").getInt("vaule");

    faceConfidence = jObj.getJSONObject("face").getInt("confidence");

    faceRect = new Rect(center, width, height);
}

From source file:org.brickred.socialauth.provider.NimbleImpl.java

/**
 * Gets the list of contacts of the user. this may not be available for all
 * providers./*from w  w  w. j  av a 2 s  .  c o m*/
 * 
 * @return List of contact objects representing Contacts. Only name will be
 *         available
 */

@Override
public List<Contact> getContactList() throws Exception {
    List<Contact> plist = new ArrayList<Contact>();
    LOG.info("Fetching contacts from " + CONTACTS_URL);
    String respStr;
    try {
        Response response = authenticationStrategy.executeFeed(CONTACTS_URL);
        respStr = response.getResponseBodyAsString(Constants.ENCODING);
    } catch (Exception e) {
        throw new SocialAuthException("Error while getting contacts from " + CONTACTS_URL, e);
    }
    try {
        LOG.debug("User Contacts list in json : " + respStr);
        JSONObject resp = new JSONObject(respStr);
        JSONArray responses = resp.getJSONArray("resources");
        LOG.debug("Found contacts : " + responses.length());
        for (int i = 0; i < responses.length(); i++) {
            JSONObject obj = responses.getJSONObject(i);
            JSONObject fields = obj.getJSONObject("fields");
            Contact p = new Contact();
            if (obj.has("record_type")) {
                if ("company".equals(obj.getString("record_type"))) {
                    if (fields.has("company name")) {
                        JSONArray arr = fields.getJSONArray("company name");
                        JSONObject jobj = arr.getJSONObject(0);
                        if (jobj.has("value")) {
                            p.setFirstName(jobj.getString("value"));
                        }
                    }
                    if (obj.has("avatar_url")) {
                        p.setProfileImageURL(obj.getString("avatar_url"));
                    }
                    if (fields.has("URL")) {
                        JSONArray arr = fields.getJSONArray("URL");
                        JSONObject jobj = arr.getJSONObject(0);
                        if (jobj.has("value")) {
                            p.setProfileUrl(jobj.getString("value"));
                        }
                    }
                    plist.add(p);
                } else if ("person".equals(obj.getString("record_type"))) {
                    if (fields.has("last name")) {
                        JSONArray arr = fields.getJSONArray("last name");
                        JSONObject jobj = arr.getJSONObject(0);
                        if (jobj.has("value")) {
                            p.setLastName(jobj.getString("value"));
                        }
                    }
                    if (fields.has("first name")) {
                        JSONArray arr = fields.getJSONArray("first name");
                        JSONObject jobj = arr.getJSONObject(0);
                        if (jobj.has("value")) {
                            p.setFirstName(jobj.getString("value"));
                        }
                    }
                    if (obj.has("avatar_url")) {
                        p.setProfileImageURL(obj.getString("avatar_url"));
                    }
                    if (fields.has("URL")) {
                        JSONArray arr = fields.getJSONArray("URL");
                        if (arr.length() == 1) {
                            JSONObject jobj = arr.getJSONObject(0);
                            if (jobj.has("value")) {
                                p.setProfileUrl(jobj.getString("value"));
                            }
                        } else {
                            String url = null;
                            for (int k = 0; k < arr.length(); k++) {
                                JSONObject jobj = arr.getJSONObject(k);
                                url = jobj.optString("value");
                                if ("personal".equals(jobj.optString("modifier"))) {
                                    break;
                                }
                            }
                            if (url != null) {
                                p.setProfileUrl(url);
                            }
                        }
                    }
                    plist.add(p);
                }
            }
        }
    } catch (Exception e) {
        throw new ServerDataException("Failed to parse the contacts json : " + respStr, e);
    }
    return plist;
}

From source file:com.geekandroid.sdk.sample.JPushReceiver.java

private static String printBundle(Bundle bundle) {
    StringBuilder sb = new StringBuilder();
    for (String key : bundle.keySet()) {
        if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
            sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
        } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
            sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
        } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
            if (bundle.getString(JPushInterface.EXTRA_EXTRA).isEmpty()) {
                Log.i(TAG, "This message has no Extra data");
                continue;
            }//from  ww  w . j  ava  2  s  . c o  m

            try {
                JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                Iterator<String> it = json.keys();

                while (it.hasNext()) {
                    String myKey = it.next().toString();
                    sb.append("\nkey:" + key + ", value: [" + myKey + " - " + json.optString(myKey) + "]");
                }
            } catch (JSONException e) {
                Log.e(TAG, "Get message extra JSON error!");
            }

        } else {
            sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
        }
    }
    return sb.toString();
}

From source file:com.google.identitytoolkit.RpcHelper.java

@VisibleForTesting
JSONObject checkGitkitException(String response) throws GitkitClientException, GitkitServerException {
    try {// ww w. j a  v  a  2s.c  o  m
        JSONObject result = new JSONObject(response);
        if (!result.has("error")) {
            return result;
        }
        // Error handling
        JSONObject error = result.getJSONObject("error");
        String code = error.optString("code");
        if (code != null) {
            if (code.startsWith("4")) {
                // 4xx means client input error
                throw new GitkitClientException(error.optString("message"));
            } else {
                throw new GitkitServerException(error.optString("message"));
            }
        }
    } catch (JSONException e) {
        log.warning("Server response exception: " + e.getMessage());
    }
    throw new GitkitServerException("null error code from Gitkit server");
}

From source file:org.mariotaku.twidere.extension.mediauploader.util.ParseUtils.java

public static Bundle jsonToBundle(final String string) {
    final Bundle bundle = new Bundle();
    if (string != null) {
        try {/*from w  w  w .  j a va 2  s. co  m*/
            final JSONObject json = new JSONObject(string);
            final Iterator<?> it = json.keys();
            while (it.hasNext()) {
                final Object key_obj = it.next();
                if (key_obj == null) {
                    continue;
                }
                final String key = key_obj.toString();
                final Object value = json.get(key);
                if (value instanceof Boolean) {
                    bundle.putBoolean(key, json.optBoolean(key));
                } else if (value instanceof Integer) {
                    // Simple workaround for account_id
                    if (shouldPutLong(key)) {
                        bundle.putLong(key, json.optLong(key));
                    } else {
                        bundle.putInt(key, json.optInt(key));
                    }
                } else if (value instanceof Long) {
                    bundle.putLong(key, json.optLong(key));
                } else if (value instanceof String) {
                    bundle.putString(key, json.optString(key));
                } else {
                    Log.w(LOGTAG,
                            "Unknown type " + value.getClass().getSimpleName() + " in arguments key " + key);
                }
            }
        } catch (final JSONException e) {
            e.printStackTrace();
        } catch (final ClassCastException e) {
            e.printStackTrace();
        }
    }
    return bundle;
}

From source file:com.github.mongo.labs.model.Speaker.java

public Speaker(String json) {
    JSONObject speaker = new JSONObject(json);

    this.name = new Name(speaker.getJSONObject("name").optString("lastName"),
            speaker.getJSONObject("name").optString("firstName"));
    this.bio = speaker.optString("bio");
}

From source file:com.github.snowdream.android.app.books.controller.BookManager.java

/**
 * Parse Book/*from w  ww.j  a v a 2s.com*/
 *
 * @param obj
 * @return
 */
private static List<BookItem> parseBook(JSONObject obj) {
    List<BookItem> list = null;

    if (obj == null) {
        return list;
    }

    try {
        list = new ArrayList<BookItem>();
        JSONArray array = obj.getJSONArray("book");
        int length = array.length();
        for (int i = 0; i < length; i++) {
            JSONObject oj = array.getJSONObject(i);

            if (oj == null) {
                continue;
            }

            BookItem item = new BookItem();
            item.setLanguage(oj.optString("language"));
            item.setCountry(oj.optString("country"));
            item.setAuthor(oj.optString("author"));
            item.setTitle(oj.optString("title"));
            item.setDesc(oj.optString("desc"));
            item.setDefault(oj.optBoolean("default"));
            item.setUrl(oj.optString("url"));
            item.setImg(oj.optString("img"));

            list.add(item);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return list;
}

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

private boolean post_filter(CSPRequestCredentials creds, CSPRequestCache cache, JSONObject restrictions,
        Node candidate) throws ExistException, UnderlyingStorageException, ConnectionException, JSONException {
    if (restrictions == null)
        return true;
    // Subject/*from w w w .j a va2s  . co  m*/
    String src_csid = candidate.selectSingleNode("subjectCsid").getText();
    String rest_src = restrictions.optString("src");
    if (rest_src != null && !"".equals(rest_src)) {
        String[] data = rest_src.split("/");
        if (data[0].equals("")) {
            rest_src = rest_src.substring(1);
            data = rest_src.split("/");
        }
        if (!src_csid.equals(rest_src.split("/")[1]))
            return false;
    }
    String dst_csid = candidate.selectSingleNode("objectCsid").getText();
    String rest_dst = restrictions.optString("dst");
    if (rest_dst != null && !"".equals(rest_dst)) {
        String[] data2 = rest_dst.split("/");
        if (data2[0].equals("")) {
            rest_dst = rest_dst.substring(1);
            data2 = rest_dst.split("/");
        }
        if (!dst_csid.equals(rest_dst.split("/")[1]))
            return false;
    }
    // Retrieve the relation (CSPACE-1081)
    ReturnedMultipartDocument rel = conn.getMultipartXMLDocument(RequestMethod.GET,
            candidate.selectSingleNode("uri").getText(), null, creds, cache);
    if (rel.getStatus() == 404)
        throw new ExistException("Not found");
    Document rel_doc = rel.getDocument("relations_common");
    if (rel_doc == null)
        throw new UnderlyingStorageException("Could not retrieve relation, missing relations_common");
    String type = rel_doc.selectSingleNode("relations_common/relationshipType").getText();
    if (restrictions.has("type") && !type.equals(restrictions.optString("type")))
        return false;
    return true;
}

From source file:de.dekarlab.moneybuilder.model.parser.JsonBookLoader.java

/**
 * Parse accounts./* w w  w.  j a va 2 s.c o  m*/
 * 
 * @param jsonFolder
 * @param folder
 */
protected static void parseAccounts(JSONObject jsonFolder, Folder folder) {
    // add attributes to current folder.
    folder.setName(jsonFolder.getString("name"));
    parseAccountValues(jsonFolder, folder);
    // ----------------
    JSONArray list = jsonFolder.getJSONArray("list");
    for (int i = 0; i < list.length(); i++) {
        JSONObject jsonNewAccount = list.getJSONObject(i);
        if (jsonNewAccount.optString("folder").equals("y")) {
            Folder newFolder = new Folder(jsonNewAccount.getInt("type"));
            parseAccountValues(jsonNewAccount, newFolder);
            parseAccounts(jsonNewAccount, newFolder);
            folder.addAccount(newFolder);
        } else {
            Account newAccount = new Account(jsonNewAccount.getInt("type"));
            parseAccountValues(jsonNewAccount, newAccount);
            newAccount.setName(jsonNewAccount.getString("name"));
            if (jsonNewAccount.optString("hidden").equals("y")) {
                newAccount.setHidden(true);
            }
            String hiddenDate = jsonNewAccount.optString("hiddenDate");
            if (hiddenDate != null) {
                newAccount.setHiddenDate(Formatter.parseDate(hiddenDate));
            }
            folder.addAccount(newAccount);
        }
    }
}

From source file:de.dekarlab.moneybuilder.model.parser.JsonBookLoader.java

/**
 * Parse value./*  w w  w .  j  a  va  2  s . co  m*/
 * 
 * @param jsonFolder
 * @return
 */
protected static Value parseValue(JSONObject jsonValue) {
    Value res = new Value();
    if (jsonValue != null) {
        double val = jsonValue.optDouble("startOfPeriod");
        if (Double.isNaN(val)) {
            val = 0.0;
        }
        res.setStartOfPeriod(val);
        val = jsonValue.optDouble("credit");
        if (Double.isNaN(val)) {
            val = 0.0;
        }
        res.setCredit(val);
        val = jsonValue.optDouble("debit");
        if (Double.isNaN(val)) {
            val = 0.0;
        }
        res.setDebit(val);
        val = jsonValue.optDouble("endOfPeriod");
        if (Double.isNaN(val)) {
            val = 0.0;
        }
        res.setEndOfPeriod(val);
        val = jsonValue.optDouble("control");
        if (Double.isNaN(val)) {
            val = 0.0;
        }
        res.setControl(val);
        if (jsonValue.optString("manual").equals("y")) {
            res.setManual(true);
        }
    }
    return res;
}