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:uk.co.pilllogger.billing.Purchase.java

public Purchase(String jsonPurchaseInfo, String signature) throws JSONException {
    mOriginalJson = jsonPurchaseInfo;// w w  w .j  a  v  a 2 s .co  m
    JSONObject o = new JSONObject(mOriginalJson);
    mOrderId = o.optString("orderId");
    mPackageName = o.optString("packageName");
    mSku = o.optString("productId");
    mPurchaseTime = o.optLong("purchaseTime");
    mPurchaseState = o.optInt("purchaseState");
    mDeveloperPayload = o.optString("developerPayload");
    mToken = o.optString("token", o.optString("purchaseToken"));
    mSignature = signature;
}

From source file:com.segma.trim.InAppBillingUtilities.StockKeepingUnitDetails.java

public StockKeepingUnitDetails(String itemType, String jsonSkuDetails) throws JSONException {
    mItemType = itemType;/*w  ww.  j av  a 2 s .  c o m*/
    mJson = jsonSkuDetails;
    JSONObject o = new JSONObject(mJson);
    mSku = o.optString("productId");
    mType = o.optString("type");
    mPrice = o.optString("price");
    mPriceAmountMicros = o.optLong("price_amount_micros");
    mPriceCurrencyCode = o.optString("price_currency_code");
    mTitle = o.optString("title");
    mDescription = o.optString("description");
}

From source file:me.calebjones.blogsite.network.PostDownloader.java

private void getPostAll() {

    //Setup the URLS that I will need
    String firstUrl = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID";
    String nextPage = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID&page_handle=";

    Request request = new Request.Builder().url(firstUrl).build();

    int count = 0;

    try {//www  .  j  a va 2 s .c  o m

        //First make a call to see how many total posts there are and save to 'found'
        final Response response = BlogsiteApplication.getInstance().client.newCall(request).execute();
        if (!response.isSuccessful()) {
            mBuilder.setContentText("Download failed.").setProgress(0, 0, false).setAutoCancel(true)
                    .setOngoing(false);
            mNotifyManager.notify(NOTIF_ID, mBuilder.build());
            throw new IOException();
        } else {

            //Take the response and parse the JSON
            JSONObject JObject = new JSONObject(response.body().string());
            JSONArray posts = JObject.optJSONArray("posts");

            //Store the data into the two objects, meta gets the next page later on.
            // Found is total post count.
            String meta = JObject.optString("meta");
            int found = JObject.optInt("found");

            postID = new ArrayList<>();

            //If there are more then 100, which there always will unless something
            // catastrophic happens then set up the newURL.
            if (found > 100) {
                JSONObject metaLink = new JSONObject(meta);
                String nextValue = metaLink.optString("next_page");
                newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");
                Log.d("The Jones Theory", newURL);
            }

            // Loop through the posts and add the post ID to the array.
            // The posts is still from the original call.
            for (int i = 0; i < posts.length(); i++) {
                JSONObject post = posts.optJSONObject(i);
                postID.add(post.optString("ID"));
                count++;
            }

            //Now this logic is in charge of loading the next pages
            // until all posts are loaded into the array.
            while (count != found) {
                Request newRequest = new Request.Builder().url(newURL).build();
                Response newResponse = BlogsiteApplication.getInstance().client.newCall(newRequest).execute();
                if (!newResponse.isSuccessful())
                    throw new IOException();

                JSONObject nJObject = new JSONObject(newResponse.body().string());
                JSONArray nPosts = nJObject.optJSONArray("posts");
                String nMeta = nJObject.optString("meta");
                int newFound = nJObject.optInt("found");

                if (newFound > 100) {
                    JSONObject metaLink = new JSONObject(nMeta);
                    String nextValue = metaLink.optString("next_page");
                    newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");
                }
                for (int i = 0; i < nPosts.length(); i++) {
                    JSONObject post = nPosts.optJSONObject(i);
                    postID.add(post.optString("ID"));
                    count++;
                }
            }
            Collections.reverse(postID);
            download(postID);
            Log.d("The Jones Theory",
                    "getPostAll - Downloading = " + SharedPrefs.getInstance().isDownloading());
        }
    } catch (IOException | JSONException e) {
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setDownloading(false);
        e.printStackTrace();
    }
}

From source file:me.calebjones.blogsite.network.PostDownloader.java

private void getPostMissing() {
    notificationService();//from  ww w. ja v  a 2s  .  com
    SharedPrefs.getInstance().setDownloading(true);
    DatabaseManager databaseManager = new DatabaseManager(this);
    //Setup the URLS that I will need
    String firstUrl = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID";
    String nextPage = "https://public-api.wordpress.com/rest/v1.1/sites/calebjones.me/posts/"
            + "?pretty=true&number=100&fields=ID,title&order_by=ID&page_handle=";
    Request request = new Request.Builder().url(firstUrl).build();
    int count = 0;

    try {

        //First make a call to see how many total posts there are and save to 'found'
        final Response response = BlogsiteApplication.getInstance().client.newCall(request).execute();
        if (!response.isSuccessful())
            throw new IOException();

        //Take the response and parse the JSON
        JSONObject JObject = new JSONObject(response.body().string());
        JSONArray posts = JObject.optJSONArray("posts");

        //Store the data into the two objects, meta gets the next page later on.
        // Found is total post count.
        String meta = JObject.optString("meta");
        int found = JObject.optInt("found");

        postID = new ArrayList<>();

        //If there are more then 100, which there always will unless something
        // catastrophic happens then set up the newURL.
        if (found > 100) {
            JSONObject metaLink = new JSONObject(meta);
            String nextValue = metaLink.optString("next_page");
            newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");
        }

        // Loop through the posts and add the post ID to the array.
        // The posts is still from the original call.
        for (int i = 0; i < posts.length(); i++) {
            JSONObject post = posts.optJSONObject(i);
            if (!databaseManager.idExists(post.optString("ID"))) {
                postID.add(post.optString("ID"));
            }
            count++;
        }

        //Now this logic is in charge of loading the next pages
        // until all posts are loaded into the array.
        while (count != found) {
            Request newRequest = new Request.Builder().url(newURL).build();
            Response newResponse = BlogsiteApplication.getInstance().client.newCall(newRequest).execute();
            if (!newResponse.isSuccessful())
                throw new IOException();

            JSONObject nJObject = new JSONObject(newResponse.body().string());
            JSONArray nPosts = nJObject.optJSONArray("posts");
            String nMeta = nJObject.optString("meta");
            int newFound = nJObject.optInt("found");

            if (newFound > 100) {
                JSONObject metaLink = new JSONObject(nMeta);
                String nextValue = metaLink.optString("next_page");
                newURL = nextPage + URLEncoder.encode(nextValue, "UTF-8");

            }

            for (int i = 0; i < nPosts.length(); i++) {
                JSONObject post = nPosts.optJSONObject(i);
                if (!databaseManager.idExists(post.optString("ID"))) {
                    postID.add(post.optString("ID"));
                }
                count++;
            }
        }
    } catch (IOException | JSONException e) {
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setDownloading(false);
        e.printStackTrace();
    }
    Collections.reverse(postID);
    download(postID);
}

From source file:me.calebjones.blogsite.network.PostDownloader.java

public void download(final List<String> postID) {
    final DatabaseManager databaseManager = new DatabaseManager(this);

    try {/*from   www . ja  va  2s . c om*/
        final int num = postID.size() - 1;
        final CountDownLatch latch = new CountDownLatch(num);
        final Executor executor = Executors.newFixedThreadPool(15);

        for (int i = 1; i <= postID.size() - 1; i++) {
            final int count = i;
            final int index = Integer.parseInt(postID.get(i));
            executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        if (index != 404) {
                            String url = String.format(POST_URL, index);
                            Request newReq = new Request.Builder().url(url).build();
                            Response newResp = BlogsiteApplication.getInstance().client.newCall(newReq)
                                    .execute();

                            if (!newResp.isSuccessful() && !(newResp.code() == 404)
                                    && !(newResp.code() == 403)) {
                                Log.e("The Jones Theory", "Error: " + newResp.code() + "URL: " + url);
                                LocalBroadcastManager.getInstance(PostDownloader.this)
                                        .sendBroadcast(new Intent(DOWNLOAD_FAIL));
                                throw new IOException();
                            }

                            if (newResp.code() == 404) {
                                return;
                            }

                            String resp = newResp.body().string();

                            JSONObject jObject = new JSONObject(resp);

                            Posts item1 = new Posts();

                            //If the item is not a post break out of loop and ignore it
                            if (!(jObject.optString("type").equals("post"))) {
                                return;
                            }
                            item1.setTitle(jObject.optString("title"));
                            item1.setContent(jObject.optString("content"));
                            item1.setExcerpt(jObject.optString("excerpt"));
                            item1.setPostID(jObject.optInt("ID"));
                            item1.setURL(jObject.optString("URL"));

                            //Parse the Date!
                            String date = jObject.optString("date");
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                            Date newDate = format.parse(date);

                            format = new SimpleDateFormat("yyyy-MM-dd");
                            date = format.format(newDate);

                            item1.setDate(date);

                            //Cuts out all the Child nodes and gets only the  tags.
                            JSONObject Tobj = new JSONObject(jObject.optString("tags"));
                            JSONArray Tarray = Tobj.names();
                            String tagsList = null;

                            if (Tarray != null && (Tarray.length() > 0)) {

                                for (int c = 0; c < Tarray.length(); c++) {
                                    if (tagsList != null) {
                                        String thisTag = Tarray.getString(c);
                                        tagsList = tagsList + ", " + thisTag;
                                    } else {
                                        String thisTag = Tarray.getString(c);
                                        tagsList = thisTag;
                                    }
                                }
                                item1.setTags(tagsList);
                            } else {
                                item1.setTags("");
                            }

                            JSONObject Cobj = new JSONObject(jObject.optString("categories"));
                            JSONArray Carray = Cobj.names();
                            String catsList = null;

                            if (Carray != null && (Carray.length() > 0)) {

                                for (int c = 0; c < Carray.length(); c++) {
                                    if (catsList != null) {
                                        String thisCat = Carray.getString(c);
                                        catsList = catsList + ", " + thisCat;
                                    } else {
                                        String thisCat = Carray.getString(c);
                                        catsList = thisCat;
                                    }
                                }
                                item1.setCategories(catsList);
                            } else {
                                item1.setCategories("");
                            }

                            Integer ImageLength = jObject.optString("featured_image").length();
                            if (ImageLength == 0) {
                                item1.setFeaturedImage(null);
                            } else {
                                item1.setFeaturedImage(jObject.optString("featured_image"));
                            }
                            if (item1 != null) {
                                databaseManager.addPost(item1);
                                Log.d("PostDownloader", index + " database...");
                                double progress = ((double) count / num) * 100;
                                setProgress((int) progress, item1.getTitle(), count);

                                Intent intent = new Intent(DOWNLOAD_PROGRESS);
                                intent.putExtra(PROGRESS, progress);
                                intent.putExtra(NUMBER, num);
                                intent.putExtra(TITLE, item1.getTitle());

                                LocalBroadcastManager.getInstance(PostDownloader.this).sendBroadcast(intent);
                            }
                        }
                    } catch (IOException | JSONException | ParseException e) {
                        if (SharedPrefs.getInstance().isFirstDownload()) {
                            SharedPrefs.getInstance().setFirstDownload(false);
                        }
                        SharedPrefs.getInstance().setDownloading(false);
                        e.printStackTrace();
                    } finally {
                        latch.countDown();
                    }
                }
            });
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            if (SharedPrefs.getInstance().isFirstDownload()) {
                SharedPrefs.getInstance().setFirstDownload(false);
            }
            SharedPrefs.getInstance().setDownloading(false);
            LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
            mBuilder.setContentText("Download failed.").setSmallIcon(R.drawable.ic_action_file_download)
                    .setAutoCancel(true).setProgress(0, 0, false).setOngoing(false);
            mNotifyManager.notify(NOTIF_ID, mBuilder.build());
            throw new IOException(e);
        }
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setDownloading(false);

        Log.d("PostDownloader", "Broadcast Sent!");
        Log.d("The Jones Theory", "download - Downloading = " + SharedPrefs.getInstance().isDownloading());

        Intent mainActIntent = new Intent(this, MainActivity.class);
        PendingIntent clickIntent = PendingIntent.getActivity(this, 57836, mainActIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_SUCCESS));
        mBuilder.setContentText("Download complete").setSmallIcon(R.drawable.ic_action_done)
                .setProgress(0, 0, false).setContentIntent(clickIntent).setAutoCancel(true).setOngoing(false);
        mNotifyManager.notify(NOTIF_ID, mBuilder.build());

    } catch (IOException e) {
        if (SharedPrefs.getInstance().isFirstDownload()) {
            SharedPrefs.getInstance().setFirstDownload(false);
        }
        SharedPrefs.getInstance().setLastRedownladTime(System.currentTimeMillis());
        SharedPrefs.getInstance().setDownloading(false);
        e.printStackTrace();
        LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(DOWNLOAD_FAIL));
        mBuilder.setContentText("Download failed.").setProgress(0, 0, false).setAutoCancel(true)
                .setOngoing(false);
        mNotifyManager.notify(NOTIF_ID, mBuilder.build());
    }
}

From source file:org.haxe.extension.iap.util.SkuDetails.java

public SkuDetails(String itemType, String jsonSkuDetails) throws JSONException {
    mItemType = itemType;//w w w  . ja  va 2 s . co  m
    mJson = jsonSkuDetails;
    JSONObject o = new JSONObject(mJson);
    mSku = o.optString("productId");
    mType = o.optString("type");
    mPrice = o.optString("price");
    mTitle = o.optString("title");
    mCurrencyCode = o.optString("price_currency_code");
    mDescription = o.optString("description");
}

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

public static Media fromJSON(JSONObject o) throws JSONException {
    if (o == null)
        return null;
    Media media = new Media();
    media.id = o.optString("id");
    media.type = o.optString("type");
    media.createdTime = o.optString("created_time");
    media.attribution = o.optString("attribution");
    media.image = Image.fromJSON(o.optJSONObject("images"));
    if (media.type.equals("video"))
        media.video = Video.fromJSON(o.optJSONObject("videos"));
    media.link = o.optString("link");
    media.filter = o.optString("filter");
    media.userHasLiked = o.optBoolean("user_has_liked");
    media.user = User.fromJSON(o.optJSONObject("user"));
    JSONArray tagsJSONArray = o.optJSONArray("tags");
    ArrayList<String> tags = new ArrayList<>();
    for (int j = 0; j < tagsJSONArray.length(); j++) {
        tags.add(tagsJSONArray.optString(j));
    }/*  ww w. ja  v a2 s  . co  m*/
    media.tags.addAll(tags);
    JSONArray likesJSONArray = o.optJSONObject("likes").optJSONArray("data");
    ArrayList<Like> likes = new ArrayList<>();
    for (int j = 0; j < likesJSONArray.length(); j++) {
        JSONObject likeJSON = (JSONObject) likesJSONArray.get(j);
        likes.add(Like.fromJSON(likeJSON));
    }
    media.likes.addAll(likes);
    JSONArray commentJSONArray = o.optJSONObject("comments").optJSONArray("data");
    ArrayList<Comment> comments = new ArrayList<>();
    for (int j = 0; j < commentJSONArray.length(); j++) {
        JSONObject commentJSON = (JSONObject) commentJSONArray.get(j);
        comments.add(Comment.fromJSON(commentJSON));
    }
    media.comments.addAll(comments);
    JSONArray usersInPhotoJSON = o.optJSONArray("users_in_photo");
    ArrayList<UserInPhoto> usersInPhotos = new ArrayList<>();
    for (int j = 0; j < usersInPhotoJSON.length(); j++) {
        JSONObject userInPhotoJSON = (JSONObject) usersInPhotoJSON.get(j);
        usersInPhotos.add(UserInPhoto.fromJSON(userInPhotoJSON));
    }
    media.usersInPhoto.addAll(usersInPhotos);
    JSONObject locationJSON = o.optJSONObject("location");
    if (locationJSON != null) {
        media.location = Location.fromJSON(locationJSON);
    }
    JSONObject captionJSON = o.optJSONObject("caption");
    if (captionJSON != null) {
        media.caption = Comment.fromJSON(captionJSON);
    }
    return media;
}

From source file:org.catnut.support.TransientUser.java

public static TransientUser convert(JSONObject jsonObject) {
    TransientUser user = new TransientUser();
    user.id = jsonObject.optLong(Constants.ID);
    user.screenName = jsonObject.optString(User.screen_name);
    user.location = jsonObject.optString(User.location);
    user.description = jsonObject.optString(User.description);
    user.verified = jsonObject.optBoolean(User.verified);
    user.avatarUrl = jsonObject.optString(User.profile_image_url);
    return user;/* w  w w. j  a  v a2  s  .  c o m*/
}

From source file:com.cpyf.twelve.spies.qr.code.book.SearchBookContentsActivity.java

private void handleSearchResults(JSONObject json) {
    try {//ww  w  .j  a  v a 2 s  . c om
        int count = json.getInt("number_of_results");
        headerView.setText("Found " + (count == 1 ? "1 result" : count + " results"));
        if (count > 0) {
            JSONArray results = json.getJSONArray("search_results");
            SearchBookContentsResult.setQuery(queryTextView.getText().toString());
            List<SearchBookContentsResult> items = new ArrayList<SearchBookContentsResult>(count);
            for (int x = 0; x < count; x++) {
                items.add(parseResult(results.getJSONObject(x)));
            }
            resultListView.setOnItemClickListener(new BrowseBookListener(this, items));
            resultListView.setAdapter(new SearchBookContentsAdapter(this, items));
        } else {
            String searchable = json.optString("searchable");
            if ("false".equals(searchable)) {
                headerView.setText(R.string.msg_sbc_book_not_searchable);
            }
            resultListView.setAdapter(null);
        }
    } catch (JSONException e) {
        Log.w(TAG, "Bad JSON from book search", e);
        resultListView.setAdapter(null);
        headerView.setText(R.string.msg_sbc_failed);
    }
}

From source file:com.cpyf.twelve.spies.qr.code.book.SearchBookContentsActivity.java

private SearchBookContentsResult parseResult(JSONObject json) {
    try {//from   w w  w  .j  av a2 s . co m
        String pageId = json.getString("page_id");
        String pageNumber = json.getString("page_number");
        if (pageNumber.length() > 0) {
            pageNumber = getString(R.string.msg_sbc_page) + ' ' + pageNumber;
        } else {
            // This can happen for text on the jacket, and possibly other
            // reasons.
            pageNumber = getString(R.string.msg_sbc_unknown_page);
        }

        // Remove all HTML tags and encoded characters. Ideally the server
        // would do this.
        String snippet = json.optString("snippet_text");
        boolean valid = true;
        if (snippet.length() > 0) {
            snippet = TAG_PATTERN.matcher(snippet).replaceAll("");
            snippet = LT_ENTITY_PATTERN.matcher(snippet).replaceAll("<");
            snippet = GT_ENTITY_PATTERN.matcher(snippet).replaceAll(">");
            snippet = QUOTE_ENTITY_PATTERN.matcher(snippet).replaceAll("'");
            snippet = QUOT_ENTITY_PATTERN.matcher(snippet).replaceAll("\"");
        } else {
            snippet = '(' + getString(R.string.msg_sbc_snippet_unavailable) + ')';
            valid = false;
        }
        return new SearchBookContentsResult(pageId, pageNumber, snippet, valid);
    } catch (JSONException e) {
        // Never seen in the wild, just being complete.
        return new SearchBookContentsResult(getString(R.string.msg_sbc_no_page_returned), "", "", false);
    }
}