Example usage for org.json JSONObject optJSONObject

List of usage examples for org.json JSONObject optJSONObject

Introduction

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

Prototype

public JSONObject optJSONObject(String key) 

Source Link

Document

Get an optional JSONObject associated with a key.

Usage

From source file:com.phonegap.ContactAccessorSdk5.java

/**
 * Creates a new contact and stores it in the database
 * /*  w w  w  . j ava 2 s.co  m*/
 * @param contact the contact to be saved
 * @param account the account to be saved under
 */
private boolean createNewContact(JSONObject contact, Account account) {
    // Create a list of attributes to add to the contact database
    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    //Add contact type
    ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
            .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, account.type)
            .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, account.name).build());

    // Add name
    try {
        JSONObject name = contact.optJSONObject("name");
        String displayName = contact.getString("displayName");
        if (displayName != null || name != null) {
            ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                    .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                    .withValue(ContactsContract.Data.MIMETYPE,
                            ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName)
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME,
                            getJsonString(name, "familyName"))
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME,
                            getJsonString(name, "middleName"))
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
                            getJsonString(name, "givenName"))
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX,
                            getJsonString(name, "honorificPrefix"))
                    .withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX,
                            getJsonString(name, "honorificSuffix"))
                    .build());
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get name object");
    }

    //Add phone numbers
    JSONArray phones = null;
    try {
        phones = contact.getJSONArray("phoneNumbers");
        if (phones != null) {
            for (int i = 0; i < phones.length(); i++) {
                JSONObject phone = (JSONObject) phones.get(i);
                insertPhone(ops, phone);
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get phone numbers");
    }

    // Add emails
    JSONArray emails = null;
    try {
        emails = contact.getJSONArray("emails");
        if (emails != null) {
            for (int i = 0; i < emails.length(); i++) {
                JSONObject email = (JSONObject) emails.get(i);
                insertEmail(ops, email);
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get emails");
    }

    // Add addresses
    JSONArray addresses = null;
    try {
        addresses = contact.getJSONArray("addresses");
        if (addresses != null) {
            for (int i = 0; i < addresses.length(); i++) {
                JSONObject address = (JSONObject) addresses.get(i);
                insertAddress(ops, address);
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get addresses");
    }

    // Add organizations
    JSONArray organizations = null;
    try {
        organizations = contact.getJSONArray("organizations");
        if (organizations != null) {
            for (int i = 0; i < organizations.length(); i++) {
                JSONObject org = (JSONObject) organizations.get(i);
                insertOrganization(ops, org);
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get organizations");
    }

    // Add IMs
    JSONArray ims = null;
    try {
        ims = contact.getJSONArray("ims");
        if (ims != null) {
            for (int i = 0; i < ims.length(); i++) {
                JSONObject im = (JSONObject) ims.get(i);
                insertIm(ops, im);
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get emails");
    }

    // Add note
    String note = getJsonString(contact, "note");
    if (note != null) {
        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Note.NOTE, note).build());
    }

    // Add nickname
    String nickname = getJsonString(contact, "nickname");
    if (nickname != null) {
        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname).build());
    }

    // Add urls   
    JSONArray websites = null;
    try {
        websites = contact.getJSONArray("websites");
        if (websites != null) {
            for (int i = 0; i < websites.length(); i++) {
                JSONObject website = (JSONObject) websites.get(i);
                insertWebsite(ops, website);
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get websites");
    }

    // Add birthday
    String birthday = getJsonString(contact, "birthday");
    if (birthday != null) {
        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Event.TYPE,
                        ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY)
                .withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday).build());
    }

    // Add photos
    JSONArray photos = null;
    try {
        photos = contact.getJSONArray("photos");
        if (photos != null) {
            for (int i = 0; i < photos.length(); i++) {
                JSONObject photo = (JSONObject) photos.get(i);
                insertPhoto(ops, photo);
            }
        }
    } catch (JSONException e) {
        Log.d(LOG_TAG, "Could not get photos");
    }

    boolean retVal = true;
    //Add contact
    try {
        mApp.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
    } catch (RemoteException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        retVal = false;
    } catch (OperationApplicationException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        retVal = false;
    }

    return retVal;
}

From source file:com.mparticle.internal.ConfigManager.java

public Map<String, String> getIntegrationAttributes(int kitId) {
    Map<String, String> integrationAttributes = new HashMap<String, String>();
    JSONObject jsonAttributes = getIntegrationAttributes();
    if (jsonAttributes != null) {
        JSONObject kitAttributes = jsonAttributes.optJSONObject(Integer.toString(kitId));
        if (kitAttributes != null) {
            try {
                Iterator<String> keys = kitAttributes.keys();
                while (keys.hasNext()) {
                    String key = keys.next();
                    if (kitAttributes.get(key) instanceof String) {
                        integrationAttributes.put(key, kitAttributes.getString(key));
                    }//www  . j  a  va 2  s  . c  om
                }
            } catch (JSONException e) {

            }
        }
    }
    return integrationAttributes;
}

From source file:com.vk.sdkweb.api.model.VKApiVideo.java

/**
 * Fills a Video instance from JSONObject.
 *//*from  www  .j a  va 2  s  .c  o  m*/
public VKApiVideo parse(JSONObject from) {
    id = from.optInt("id");
    owner_id = from.optInt("owner_id");
    title = from.optString("title");
    description = from.optString("description");
    duration = from.optInt("duration");
    link = from.optString("link");
    date = from.optLong("date");
    views = from.optInt("views");
    comments = from.optInt("comments");
    player = from.optString("player");
    access_key = from.optString("access_key");
    album_id = from.optInt("album_id");

    JSONObject likes = from.optJSONObject("likes");
    if (likes != null) {
        this.likes = likes.optInt("count");
        user_likes = parseBoolean(likes, "user_likes");
    }
    can_comment = parseBoolean(from, "can_comment");
    can_repost = parseBoolean(from, "can_repost");
    repeat = parseBoolean(from, "repeat");

    privacy_view = VKPrivacy.parsePrivacy(from.optJSONObject("privacy_view"));
    privacy_comment = VKPrivacy.parsePrivacy(from.optJSONObject("privacy_comment"));

    JSONObject files = from.optJSONObject("files");
    if (files != null) {
        mp4_240 = files.optString("mp4_240");
        mp4_360 = files.optString("mp4_360");
        mp4_480 = files.optString("mp4_480");
        mp4_720 = files.optString("mp4_720");
        external = files.optString("external");
    }

    photo_130 = from.optString("photo_130");
    if (!TextUtils.isEmpty(photo_130)) {
        photo.add(VKApiPhotoSize.create(photo_130, 130));
    }

    photo_320 = from.optString("photo_320");
    if (!TextUtils.isEmpty(photo_320)) {
        photo.add(VKApiPhotoSize.create(photo_320, 320));
    }

    photo_640 = from.optString("photo_640");
    if (!TextUtils.isEmpty(photo_640)) {
        photo.add(VKApiPhotoSize.create(photo_640, 640));
    }
    return this;
}

From source file:com.company.project.core.connector.HttpClientHelper.java

/**
 * for good response/*from   ww w.j  a  v  a2 s.  com*/
 * 
 * @param responseCode
 * @param responseMsg
 * @return
 * @throws JSONException
 */
public static JSONObject processBadRespStr(int responseCode, String responseMsg) throws JSONException {

    JSONObject response = new JSONObject();
    response.put("responseCode", responseCode);
    if (responseMsg.equalsIgnoreCase("")) { // good response is empty string
        response.put("responseMsg", "");
    } else { // bad response is json string
        JSONObject errorObject = new JSONObject(responseMsg).optJSONObject("odata.error");

        String errorCode = errorObject.optString("code");
        String errorMsg = errorObject.optJSONObject("message").optString("value");
        response.put("responseCode", responseCode);
        response.put("errorCode", errorCode);
        response.put("errorMsg", errorMsg);
    }

    return response;
}

From source file:org.catnut.metadata.Status.java

@Override
public ContentValues convert(JSONObject json) {
    ContentValues tweet = new ContentValues();
    tweet.put(BaseColumns._ID, json.optLong(Constants.ID));
    tweet.put(created_at, json.optString(created_at));
    // ?jsonsql???
    tweet.put(columnText, json.optString(text));
    tweet.put(source, json.optString(source));
    tweet.put(favorited, json.optBoolean(favorited));
    tweet.put(truncated, json.optBoolean(truncated));
    // ??????/*from   ww  w .j  av  a 2s.com*/
    JSONArray thumbs = json.optJSONArray(pic_urls);
    if (thumbs != null) {
        // json
        tweet.put(pic_urls, thumbs.toString());
    }
    tweet.put(thumbnail_pic, json.optString(thumbnail_pic));
    tweet.put(bmiddle_pic, json.optString(bmiddle_pic));
    tweet.put(original_pic, json.optString(original_pic));
    // ???
    if (json.has(retweeted_status)) {
        tweet.put(retweeted_status, json.optJSONObject(retweeted_status).toString());
    }
    // 
    if (json.has(User.SINGLE)) {
        tweet.put(uid, json.optJSONObject(User.SINGLE).optLong(Constants.ID));
    } else if (json.has(uid)) {
        tweet.put(uid, json.optLong(uid));
    }
    tweet.put(reposts_count, json.optInt(reposts_count));
    tweet.put(comments_count, json.optInt(comments_count));
    tweet.put(attitudes_count, json.optInt(attitudes_count));
    return tweet;
}

From source file:fr.immotronic.ubikit.pems.enocean.impl.item.data.EEPA512xxDataImpl.java

public static EEPA512xxDataImpl constructDataFromRecord(int EEPType, JSONObject lastKnownData) {
    if (lastKnownData == null)
        return new EEPA512xxDataImpl(EEPType, null, null);

    Channel[] lastChannels;/*w w  w .j a v  a2 s .com*/
    switch (EEPType) {
    case 0x00:
        lastChannels = new Channel[15];
        break;
    default:
        lastChannels = new Channel[1];
        break;
    }

    try {
        for (int i = 0; i < lastChannels.length; i++) {
            JSONObject o = lastKnownData.optJSONObject("channel" + i);
            if (o == null)
                lastChannels[i] = null;
            else
                lastChannels[i] = new Channel(o);
        }

        Date date = new Date(lastKnownData.getLong("date"));

        return new EEPA512xxDataImpl(EEPType, lastChannels, date);
    } catch (JSONException e) {
        Logger.error(LC.gi(), null,
                "constructDataFromRecord(): An exception while building a sensorData from a JSONObject SHOULD never happen. Check the code !",
                e);
        return new EEPA512xxDataImpl(EEPType, null, null);
    }
}

From source file:com.vk.sdkweb.api.model.VKApiPhotoAlbum.java

/**
 * Creates a PhotoAlbum instance from JSONObject.
 */// w w  w. java2s  .  c om
public VKApiPhotoAlbum parse(JSONObject from) {
    id = from.optInt("id");
    thumb_id = from.optInt("thumb_id");
    owner_id = from.optInt("owner_id");
    title = from.optString("title");
    description = from.optString("description");
    created = from.optLong("created");
    updated = from.optLong("updated");
    size = from.optInt("size");
    can_upload = ParseUtils.parseBoolean(from, "can_upload");
    thumb_src = from.optString("thumb_src");
    if (from.has("privacy")) {
        privacy = from.optInt("privacy");
    } else {
        privacy = VKPrivacy.parsePrivacy(from.optJSONObject("privacy_view"));
    }
    JSONArray sizes = from.optJSONArray("sizes");
    if (sizes != null) {
        photo.fill(sizes);
    } else {
        photo.add(VKApiPhotoSize.create(COVER_S, 75, 55));
        photo.add(VKApiPhotoSize.create(COVER_M, 130, 97));
        photo.add(VKApiPhotoSize.create(COVER_X, 432, 249));
        photo.sort();
    }
    return this;
}

From source file:com.vk.sdkweb.api.model.VKApiCommunityFull.java

public VKApiCommunityFull parse(JSONObject jo) {
    super.parse(jo);

    JSONObject city = jo.optJSONObject(CITY);
    if (city != null) {
        this.city = new VKApiCity().parse(city);
    }/* w  w  w .  j  a  v  a 2s .  c o  m*/
    JSONObject country = jo.optJSONObject(COUNTRY);
    if (country != null) {
        this.country = new VKApiCountry().parse(country);
    }

    JSONObject place = jo.optJSONObject(PLACE);
    if (place != null)
        this.place = new VKApiPlace().parse(place);

    description = jo.optString(DESCRIPTION);
    wiki_page = jo.optString(WIKI_PAGE);
    members_count = jo.optInt(MEMBERS_COUNT);

    JSONObject counters = jo.optJSONObject(COUNTERS);
    if (counters != null)
        this.counters = new Counters(place);

    start_date = jo.optLong(START_DATE);
    end_date = jo.optLong(END_DATE);
    can_post = ParseUtils.parseBoolean(jo, CAN_POST);
    can_see_all_posts = ParseUtils.parseBoolean(jo, CAN_SEE_ALL_POSTS);
    status = jo.optString(STATUS);

    JSONObject status_audio = jo.optJSONObject("status_audio");
    if (status_audio != null)
        this.status_audio = new VKApiAudio().parse(status_audio);

    contacts = new VKList<Contact>(jo.optJSONArray(CONTACTS), Contact.class);
    links = new VKList<Link>(jo.optJSONArray(LINKS), Link.class);
    fixed_post = jo.optInt(FIXED_POST);
    verified = ParseUtils.parseBoolean(jo, VERIFIED);
    blacklisted = ParseUtils.parseBoolean(jo, VERIFIED);
    site = jo.optString(SITE);
    return this;
}

From source file:com.androidquery.simplefeed.util.JsonUtility.java

public static String getString(JSONObject jo, String... names) {

    for (int i = 0; i < names.length - 1; i++) {
        jo = jo.optJSONObject(names[i]);
        if (jo == null)
            return null;
    }/* w  ww. ja v  a 2  s . co  m*/

    return jo.optString(names[names.length - 1], null);

}

From source file:com.melniqw.instagramsdk.Video.java

public static Video fromJSON(JSONObject o) throws JSONException {
    if (o == null)
        return null;
    Video video = new Video();
    JSONObject lowResolutionJSON = o.optJSONObject("low_resolution");
    video.lowResolution.url = lowResolutionJSON.optString("url");
    video.lowResolution.width = lowResolutionJSON.optInt("width");
    video.lowResolution.height = lowResolutionJSON.optInt("height");
    JSONObject standartResolutionJSON = o.optJSONObject("standard_resolution");
    video.standartResolution.url = standartResolutionJSON.optString("url");
    video.standartResolution.width = standartResolutionJSON.optInt("width");
    video.standartResolution.height = standartResolutionJSON.optInt("height");
    JSONObject lowBandwidthJSON = o.optJSONObject("low_bandwidth");
    video.lowBandwidth.url = lowBandwidthJSON.optString("url");
    video.lowBandwidth.width = lowBandwidthJSON.optInt("width");
    video.lowBandwidth.height = lowBandwidthJSON.optInt("height");
    return video;
}