Example usage for org.json JSONObject optJSONArray

List of usage examples for org.json JSONObject optJSONArray

Introduction

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

Prototype

public JSONArray optJSONArray(String key) 

Source Link

Document

Get an optional JSONArray associated with a key.

Usage

From source file:com.samsung.richnotification.RichNotificationHelper.java

private static SrnRemoteInputAction getRemoteInputAction(Context mContext, JSONObject action)
        throws JSONException {
    SrnRemoteInputAction inputAction = null;
    String actionLabel = action.optString("actionLabel");
    if (actionLabel == null || actionLabel.isEmpty())
        return null;

    inputAction = new SrnRemoteInputAction(actionLabel);

    int inputType = action.optInt("type");
    switch (inputType) {
    case ACTION_TYPE_INPUT_KEYBOARD:
        KeyboardInputMode kbInput = InputModeFactory.createKeyboardInputMode();
        String prefillString = action.optString("body");
        int charLimit = action.optInt("charLimit", 0);
        if (charLimit > 0 && charLimit <= prefillString.length()) {
            kbInput.setCharacterLimit(charLimit);
            kbInput.setPrefillString(prefillString.substring(0, charLimit));
        } else if (charLimit > 0 && charLimit > prefillString.length()) {
            kbInput.setCharacterLimit(charLimit);
            kbInput.setPrefillString(prefillString);
        } else {//from  ww  w . ja  va 2  s .c  om
            kbInput.setPrefillString(prefillString);
        }
        int keyboardType = action.optInt("keyboardType", KEYBOARD_NORMAL);
        kbInput.setKeyboardType(getKeyboardType(keyboardType));
        inputAction.setRequestedInputMode(kbInput);
        break;
    case ACTION_TYPE_INPUT_SINGLE_SELECT:
    case ACTION_TYPE_INPUT_MULTI_SELECT:
        SingleSelectInputMode single = InputModeFactory.createSingleSelectInputMode();
        MultiSelectInputMode multi = InputModeFactory.createMultiSelectInputMode();
        JSONArray choices = action.optJSONArray("choices");
        Log.d(TAG, "Choices: " + choices);
        if (choices == null || choices.length() == 0)
            return null;

        for (int index = 0; index < choices.length(); index++) {
            JSONObject choice = choices.optJSONObject(index);
            Log.d(TAG, "Choice: " + choice);
            if (choice == null)
                continue;

            String choiceLabel = choice.optString("choiceLabel", null);
            String choiceID = choice.optString("choiceID", null);
            if (choiceLabel == null || choiceID == null)
                continue;

            Bitmap chIco = getIconBitmap(mContext, "file://" + choice.optString("choiceIcon"));
            Log.d(TAG, "chIco for '" + choiceLabel + "'' : " + chIco);
            SrnImageAsset choiceImg = new SrnImageAsset(mContext, choiceLabel, chIco);

            boolean selected = choice.optBoolean("selected");
            if (inputType == ACTION_TYPE_INPUT_SINGLE_SELECT) {
                single.addChoice(choiceLabel, choiceID, choiceImg);
                inputAction.setRequestedInputMode(single);
            } else {
                multi.addChoice(choiceLabel, choiceID, choiceImg, selected);
                inputAction.setRequestedInputMode(multi);
            }
        }

        break;
    default:
        Log.d(TAG, "Invalid input type. Hence, ignoring.");
        return null;
    }
    return inputAction;
}

From source file:com.danlvse.weebo.model.Favorite.java

public static Favorite parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }//  www. java2 s  .c  o m

    Favorite favorite = new Favorite();
    favorite.status = Feed.parse(jsonObject.optJSONObject("status"));
    favorite.favorited_time = jsonObject.optString("favorited_time");

    JSONArray jsonArray = jsonObject.optJSONArray("tags");
    if (jsonArray != null && jsonArray.length() > 0) {
        int length = jsonArray.length();
        favorite.tags = new ArrayList<Tag>(length);
        for (int ix = 0; ix < length; ix++) {
            favorite.tags.add(Tag.parse(jsonArray.optJSONObject(ix)));
        }
    }

    return favorite;
}

From source file:io.s4.client.GenericJsonClientStub.java

@Override
public EventWrapper eventWrapperFromBytes(byte[] v) {
    try {/*  w w w.java2s  . c  om*/
        // interpret v as a JSON string
        String s = new String(v, Charset.forName("UTF8"));
        JSONObject json = new JSONObject(s);

        String streamName = json.getString("stream");
        String className = json.getString("class");

        Class<?> clazz;
        try {
            clazz = Class.forName(className);
        } catch (ClassNotFoundException e) {
            throw new ObjectBuilder.Exception("bad class name for json-encoded object: " + className, e);
        }

        String[] keyNames = null;
        JSONArray keyArray = json.optJSONArray("keys");
        if (keyArray != null) {
            keyNames = new String[keyArray.length()];
            for (int i = 0; i < keyNames.length; ++i) {
                keyNames[i] = keyArray.optString(i);
            }
        }

        String jevent = json.getString("object");

        Object obj = GsonUtil.get().fromJson(jevent, clazz);

        return new EventWrapper(streamName, keyNames, obj);

    } catch (JSONException e) {
        logger.error("problem with event JSON", e);
    } catch (ObjectBuilder.Exception e) {
        logger.error("failed to build object from JSON", e);
    }

    return null;
}

From source file:org.changhong.Note.java

public Note(JSONObject json) {

    // These methods return an empty string if the key is not found
    setTitle(XmlUtils.unescape(json.optString("title")));
    setGuid(json.optString("guid"));
    setLastChangeDate(json.optString("last-change-date"));
    String newXMLContent = json.optString("note-content");
    setXmlContent(newXMLContent);//from ww  w.  ja  v a 2  s  . c om
    JSONArray jtags = json.optJSONArray("tags");
    String tag;
    tags = new String();
    if (jtags != null) {
        for (int i = 0; i < jtags.length(); i++) {
            tag = jtags.optString(i);
            tags += tag + ",";
        }
    }
}

From source file:com.xgf.inspection.qrcode.google.zxing.client.result.supplement.BookResultInfoRetriever.java

@Override
void retrieveSupplementalInfo() throws IOException {

    CharSequence contents = HttpHelper.downloadViaHttp(
            "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
        return;//from w w  w . java  2  s  . co m
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

        JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
        JSONArray items = topLevel.optJSONArray("items");
        if (items == null || items.isNull(0)) {
            return;
        }

        JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
        if (volumeInfo == null) {
            return;
        }

        title = volumeInfo.optString("title");
        pages = volumeInfo.optString("pageCount");

        JSONArray authorsArray = volumeInfo.optJSONArray("authors");
        if (authorsArray != null && !authorsArray.isNull(0)) {
            authors = new ArrayList<String>(authorsArray.length());
            for (int i = 0; i < authorsArray.length(); i++) {
                authors.add(authorsArray.getString(i));
            }
        }

    } catch (JSONException e) {
        throw new IOException(e.toString());
    }

    Collection<String> newTexts = new ArrayList<String>();

    if (title != null && title.length() > 0) {
        newTexts.add(title);
    }

    if (authors != null && !authors.isEmpty()) {
        boolean first = true;
        StringBuilder authorsText = new StringBuilder();
        for (String author : authors) {
            if (first) {
                first = false;
            } else {
                authorsText.append(", ");
            }
            authorsText.append(author);
        }
        newTexts.add(authorsText.toString());
    }

    if (pages != null && pages.length() > 0) {
        newTexts.add(pages + "pp.");
    }

    String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}

From source file:gov.sfmta.sfpark.MyAnnotation.java

public int iconFinder(boolean showPrice) throws JSONException {
    int itemImageName = 0;
    if (onStreet) {
        return itemImageName;
    }//from  www. ja  va 2s.com

    JSONObject rates = allGarageData.optJSONObject(RATES_KEY);
    String type = allGarageData.optString(TYPE_KEY);
    int used = allGarageData.optInt(OCC_KEY, 0);
    int capacity = allGarageData.optInt(OPER_KEY, 0);
    int avail = capacity - used;
    int availpercent = 0;

    boolean invalidData = true;

    if (capacity == 0) {
        availpercent = 0;
        invalidData = true;
    } else {
        availpercent = Math.round((((float) avail / (float) capacity) * 100) * 10) / 10;
        invalidData = false;
    }

    int usedpercent = 100 - availpercent;

    if (avail < 2 && avail > 0 && availpercent != 0 && capacity <= 3) {
        if (availpercent <= 15) {
            usedpercent = -57; // less than 15 percent available. hack
        } else {
            usedpercent = -58; // more than 15 percent available. hack
        }
    } else if (capacity == 0 && used == 0 && "ON".equals(type)) {
        // On street parking, force it to red as capacity is zero
        usedpercent = -42;
    }

    // since the code above and code below is adapted from
    // two different functions from webmap.js this
    // variable links amountUsed and usedpercent to keep
    // the source code consistent here in the java version
    // where the two functions are basically fused
    // together. This is a hack on a hack. *sigh*
    int amountUsed = usedpercent;
    if (invalidData) {
        itemImageName = invalid_garage;
    } else if (amountUsed > 90 || amountUsed == -42) {
        itemImageName = garage_availability_low;
    } else if ((amountUsed <= 90 && amountUsed >= 70) || amountUsed == -58) {
        itemImageName = garage_availability_medium;
    } else if ((amountUsed < 70 && amountUsed >= 0) || amountUsed == -57) {
        itemImageName = garage_availability_high;
    }

    // modified so that negative available spaces will show as red, not grey:
    if (amountUsed == -1 || amountUsed == -2) {
        itemImageName = invalid_garage;
    }

    // New rule: if available > capacity, show grey not red
    if (avail > capacity)
        itemImageName = invalid_garage;

    // Save garage availability color even if we're on a price page,
    // because we may need it for the details page:
    switch (itemImageName) {
    case garage_availability_high:
        garageColor = availHigh;
        break;
    case garage_availability_medium:
        garageColor = availMed;
        break;
    case garage_availability_low:
        garageColor = availLow;
        break;
    default: // invalid
        garageColor = grey;
        break;
    }

    if (showPrice) {
        if (rates != null) {
            JSONArray rateArray = rates.optJSONArray(RS_KEY);
            if (!(rateArray == null)) {
                boolean isDynamicPricing = true;
                int rsc = rateArray.length();
                for (int i = 0; i < rsc; i++) {
                    JSONObject rateObject = rateArray.getJSONObject(i);
                    float phr = (float) rateObject.optDouble(RATE_KEY, 0);
                    String description = rateObject.optString(DESC_KEY);
                    if (description != null) {
                        if (description.contains(INCREMENTAL_STR)) {
                            itemImageName = nameFinder(phr);
                            isDynamicPricing = false;
                            pricePerHour = phr;
                            break;
                        }
                    }
                }

                if (isDynamicPricing) {
                    for (int i = 0; i < rsc; i++) {
                        JSONObject rateObject = rateArray.getJSONObject(i);
                        float phr = (float) rateObject.optDouble(RATE_KEY, 0);
                        rateStructureHandle(rateObject);
                        if (inThisBucketBegin(beg, end)) {
                            itemImageName = nameFinder(phr);
                            pricePerHour = phr;
                            break;
                        }
                    }
                }
            }
        }
    }
    rateQualifier = rq;
    return itemImageName;
}

From source file:gov.sfmta.sfpark.MyAnnotation.java

/** Populate the rate fields: rq,rate,beg,end
 *
 * @return line color associated with price at this time; or red if restricted.
 *///www  . jav a2s . c  o  m
int fetchRates() throws JSONException {
    int lineColor = grey;

    if (allGarageData.has(RATES_KEY)) {
        JSONObject rates = allGarageData.getJSONObject(RATES_KEY);
        // Get an optional JSONArray associated with a key. It
        // returns null if there is no such key, or if its
        // value is not a JSONArray.
        JSONArray rateArray = rates.optJSONArray(RS_KEY);
        if (!(rateArray == null)) {
            int rsc = rateArray.length();
            for (int i = 0; i < rsc; i++) {
                JSONObject rateObject = rateArray.getJSONObject(i);
                rateStructureHandle(rateObject);
                if (inThisBucketBegin(beg, end)) {
                    lineColor = bucketFinder(Float.parseFloat(rate));
                    break;
                }
            }
        } else {
            JSONObject rateObject = rates.optJSONObject(RS_KEY);
            if (!(rateObject == null)) {
                rateStructureHandle(rateObject);
                if (inThisBucketBegin(beg, end)) {
                    lineColor = bucketFinder(Float.parseFloat(rate));
                }
            } else {
                Log.v(TAG, "Fail... rateStructure isn't a dictionary or array.");
            }
        }
    } else {
        Log.v(TAG, "Fail... No rate information...");
    }

    // Restricted is always RED.
    if (NOPARKING_SET.contains(rq)) {
        lineColor = grey;
    }

    return lineColor;
}

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

/**
 * Fills a Chat instance from JSONObject.
 *///from  w ww .  j ava  2s .  c o m
public VKApiChat parse(JSONObject source) {
    id = source.optInt("id");
    type = source.optString("type");
    title = source.optString("title");
    admin_id = source.optInt("admin_id");
    JSONArray users = source.optJSONArray("users");
    if (users != null) {
        this.users = new int[users.length()];
        for (int i = 0; i < this.users.length; i++) {
            this.users[i] = users.optInt(i);
        }
    }
    return this;
}

From source file:com.jelly.music.player.GMusicHelpers.QueryResults.java

@Override
public QueryResults fromJsonObject(JSONObject jsonObject) {
    if (jsonObject != null) {
        JSONArray jsonArray = jsonObject.optJSONArray("artists");
        mArtists = (ArrayList<WebClientSongsSchema>) fromJsonArray(jsonArray);

        jsonArray = jsonObject.optJSONArray("albums");
        mAlbums = (ArrayList<WebClientSongsSchema>) fromJsonArray(jsonArray);

        jsonArray = jsonObject.optJSONArray("songs");
        mWebClientSongsSchemas = (ArrayList<WebClientSongsSchema>) fromJsonArray(jsonArray);
    }/*  ww  w  . j a  va  2 s.  c om*/

    // return this object to allow chaining
    return this;
}

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 {//from   w w w  . jav a 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();
    }
}