Example usage for org.json JSONObject optInt

List of usage examples for org.json JSONObject optInt

Introduction

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

Prototype

public int optInt(String key) 

Source Link

Document

Get an optional int value associated with a key, or zero if there is no such key or if the value is not a number.

Usage

From source file:com.example.protocol.STATUSES.java

public void fromJson(JSONObject jsonObject) throws JSONException {
    if (null == jsonObject) {
        return;/*from   ww w .j a  va  2  s. com*/
    }

    JSONArray subItemArray;

    this.comments_count = jsonObject.optInt("comments_count");

    this.text = jsonObject.optString("text");

    this.in_reply_to_screen_name = jsonObject.optString("in_reply_to_screen_name");

    this.truncated = jsonObject.optBoolean("truncated");

    this.bmiddle_pic = jsonObject.optString("bmiddle_pic");

    this.thumbnail_pic = jsonObject.optString("thumbnail_pic");

    this.source = jsonObject.optString("source");

    this.favorited = jsonObject.optBoolean("favorited");

    this.original_pic = jsonObject.optString("original_pic");

    this.in_reply_to_status_id = jsonObject.optString("in_reply_to_status_id");

    this.reposts_count = jsonObject.optInt("reposts_count");

    this.created_at = jsonObject.optString("created_at");

    this.in_reply_to_user_id = jsonObject.optString("in_reply_to_user_id");

    subItemArray = jsonObject.optJSONArray("annotations");
    if (null != subItemArray) {
        for (int i = 0; i < subItemArray.length(); i++) {
            String subItemObject = subItemArray.optString(i);
            String subItem = subItemObject;
            this.annotations.add(subItem);
        }
    }

    this.mid = jsonObject.optString("mid");
    USER user = new USER();
    user.fromJson(jsonObject.optJSONObject("user"));
    this.user = user;
    return;
}

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

/**
 * Fills a Post instance from JSONObject.
 *//*from w  ww  .  java  2s.com*/
public VKApiPost parse(JSONObject source) throws JSONException {
    id = source.optInt("id");
    to_id = source.optInt("to_id");
    from_id = source.optInt("from_id");
    date = source.optLong("date");
    text = source.optString("text");
    reply_owner_id = source.optInt("reply_owner_id");
    reply_post_id = source.optInt("reply_post_id");
    friends_only = ParseUtils.parseBoolean(source, "friends_only");
    JSONObject comments = source.optJSONObject("comments");
    if (comments != null) {
        comments_count = comments.optInt("count");
        can_post_comment = ParseUtils.parseBoolean(comments, "can_post");
    }
    JSONObject likes = source.optJSONObject("likes");
    if (likes != null) {
        likes_count = likes.optInt("count");
        user_likes = ParseUtils.parseBoolean(likes, "user_likes");
        can_like = ParseUtils.parseBoolean(likes, "can_like");
        can_publish = ParseUtils.parseBoolean(likes, "can_publish");
    }
    JSONObject reposts = source.optJSONObject("reposts");
    if (reposts != null) {
        reposts_count = reposts.optInt("count");
        user_reposted = ParseUtils.parseBoolean(reposts, "user_reposted");
    }
    post_type = source.optString("post_type");
    attachments.fill(source.optJSONArray("attachments"));
    JSONObject geo = source.optJSONObject("geo");
    if (geo != null) {
        this.geo = new VKApiPlace().parse(geo);
    }
    signer_id = source.optInt("signer_id");
    copy_history = new VKList<VKApiPost>(source.optJSONArray("copy_history"), VKApiPost.class);
    return this;
}

From source file:com.mifos.mifosxdroid.dialogfragments.loanaccountdisbursement.LoanAccountDisbursement.java

@Override
public void showLoanTemplate(ResponseBody result) {

    final ArrayList<PaymentTypeOptions> paymentOption = new ArrayList<PaymentTypeOptions>();
    final ArrayList<String> paymentNames = new ArrayList<String>();
    BufferedReader reader = null;
    StringBuilder sb = new StringBuilder();
    String line;//from  w w w.j  a v a2 s.  co m
    try {
        reader = new BufferedReader(new InputStreamReader(result.byteStream()));
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        JSONObject obj = new JSONObject(sb.toString());
        if (obj.has("paymentTypeOptions")) {
            JSONArray paymentOptions = obj.getJSONArray("paymentTypeOptions");
            for (int i = 0; i < paymentOptions.length(); i++) {
                JSONObject paymentObject = paymentOptions.getJSONObject(i);
                PaymentTypeOptions payment = new PaymentTypeOptions();
                payment.setId(paymentObject.optInt("id"));
                payment.setName(paymentObject.optString("name"));
                paymentOption.add(payment);
                paymentNames.add(paymentObject.optString("name"));
                paymentNameIdHashMap.put(payment.getName(), payment.getId());
            }
        }
        String stringResult = sb.toString();
    } catch (Exception e) {
        Log.e(LOG_TAG, "", e);
    }
    ArrayAdapter<String> paymentAdapter = new ArrayAdapter<String>(getActivity(),
            android.R.layout.simple_spinner_item, paymentNames);
    paymentAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    sp_payment_type.setAdapter(paymentAdapter);
    sp_payment_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            paymentTypeId = paymentNameIdHashMap.get(paymentNames.get(i));
            Log.d("paymentId " + paymentNames.get(i), String.valueOf(paymentTypeId));
            if (paymentTypeId != -1) {

            } else {

                Toast.makeText(getActivity(), getString(R.string.error_select_payment), Toast.LENGTH_SHORT)
                        .show();

            }

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });
}

From source file:com.facebook.internal.FacebookRequestErrorClassification.java

private static Map<Integer, Set<Integer>> parseJSONDefinition(JSONObject definition) {
    JSONArray itemsArray = definition.optJSONArray("items");
    if (itemsArray.length() == 0) {
        return null;
    }/*  w  ww  .j  ava  2s .c  om*/

    Map<Integer, Set<Integer>> items = new HashMap<>();
    for (int i = 0; i < itemsArray.length(); i++) {
        JSONObject item = itemsArray.optJSONObject(i);
        if (item == null) {
            continue;
        }
        int code = item.optInt("code");
        if (code == 0) {
            continue;
        }
        Set<Integer> subcodes = null;
        JSONArray subcodesArray = item.optJSONArray("subcodes");
        if (subcodesArray != null && subcodesArray.length() > 0) {
            subcodes = new HashSet<>();
            for (int j = 0; j < subcodesArray.length(); j++) {
                int subCode = subcodesArray.optInt(j);
                if (subCode != 0) {
                    subcodes.add(subCode);
                }
            }
        }
        items.put(code, subcodes);
    }
    return items;
}

From source file:com.example.m.niceproject.data.Condition.java

@Override
public void populate(JSONObject data) {
    code = data.optInt("code");
    temperature = data.optInt("temp");
    description = data.optString("text");
}

From source file:com.chaosinmotion.securechat.network.SCNetwork.java

private synchronized void sendRequest(final Request request) {
    callQueue.add(request);//from  ww w  .ja  va 2  s  .c  o m

    // If not in background, spin the spinner
    if (request.caller instanceof WaitSpinner) {
        ((WaitSpinner) request.caller).startWaitSpinner();
        request.waitFlag = true;
    }

    request.taskFuture = ThreadPool.get().enqueueAsync(new Runnable() {
        @Override
        public void run() {
            try {
                HttpURLConnection conn = requestWith(request);

                conn.connect();
                Map<String, List<String>> headers = conn.getHeaderFields();
                List<String> clist = headers.get("Set-Cookie");
                if (clist != null) {
                    for (String cookie : clist) {
                        cookies.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
                    }
                }

                InputStream is = conn.getInputStream();
                JSONObject d = parseResult(is);
                conn.disconnect();

                final Response response = new Response();
                response.serverCode = conn.getResponseCode();
                if (d != null) {
                    response.success = d.optBoolean("success");
                    response.error = d.optInt("error");
                    response.errorMessage = d.optString("message");
                    response.exceptionStack = d.optJSONArray("exception");
                    response.data = d.optJSONObject("data");
                }

                ThreadPool.get().enqueueMain(new Runnable() {
                    @Override
                    public void run() {
                        if (request.waitFlag && ((request.caller instanceof WaitSpinner))) {
                            ((WaitSpinner) request.caller).stopWaitSpinner();
                            request.waitFlag = false;
                        }
                        callQueue.remove(request);
                        handleResponse(response, request);
                    }
                });
            } catch (Exception ex) {
                /*
                 *  This happens if there is a connection error.
                 */
                ThreadPool.get().enqueueMain(new Runnable() {
                    @Override
                    public void run() {
                        if (request.waitFlag && ((request.caller instanceof WaitSpinner))) {
                            ((WaitSpinner) request.caller).stopWaitSpinner();
                            request.waitFlag = false;
                        }
                        callQueue.remove(request);
                        handleIOError(request);
                    }
                });
            }
        }
    });
}

From source file:com.basetechnology.s0.agentserver.field.FloatField.java

public static Field fromJson(SymbolTable symbolTable, JSONObject fieldJson) {
    String type = fieldJson.optString("type");
    if (type == null || !type.equals("float"))
        return null;
    String name = fieldJson.has("name") ? fieldJson.optString("name") : null;
    String label = fieldJson.has("label") ? fieldJson.optString("label") : null;
    String description = fieldJson.has("description") ? fieldJson.optString("description") : null;
    double defaultValue = fieldJson.has("default_value") ? fieldJson.optDouble("default_value") : 0;
    double minValue = fieldJson.has("min_value") ? fieldJson.optDouble("min_value") : Double.MIN_VALUE;
    double maxValue = fieldJson.has("max_value") ? fieldJson.optDouble("max_value") : Double.MAX_VALUE;
    int nominalWidth = fieldJson.has("nominal_width") ? fieldJson.optInt("nominal_width") : 0;
    String compute = fieldJson.has("compute") ? fieldJson.optString("compute") : null;
    return new FloatField(symbolTable, name, label, description, defaultValue, minValue, maxValue, nominalWidth,
            compute);/*from   www.  j  av a  2  s.com*/
}

From source file:com.example.wcl.test_weiboshare.Status.java

public static Status parse(JSONObject jsonObject) {
    if (null == jsonObject) {
        return null;
    }/*from   w w w. j a va  2s . c  om*/

    Status status = new Status();
    status.created_at = jsonObject.optString("created_at");
    status.id = jsonObject.optString("id");
    status.mid = jsonObject.optString("mid");
    status.idstr = jsonObject.optString("idstr");
    status.text = jsonObject.optString("text");
    status.source = jsonObject.optString("source");
    status.favorited = jsonObject.optBoolean("favorited", false);
    status.truncated = jsonObject.optBoolean("truncated", false);

    // Have NOT supported
    status.in_reply_to_status_id = jsonObject.optString("in_reply_to_status_id");
    status.in_reply_to_user_id = jsonObject.optString("in_reply_to_user_id");
    status.in_reply_to_screen_name = jsonObject.optString("in_reply_to_screen_name");

    status.thumbnail_pic = jsonObject.optString("thumbnail_pic");
    status.bmiddle_pic = jsonObject.optString("bmiddle_pic");
    status.original_pic = jsonObject.optString("original_pic");
    status.geo = Geo.parse(jsonObject.optJSONObject("geo"));
    status.user = User.parse(jsonObject.optJSONObject("user"));
    status.retweeted_status = Status.parse(jsonObject.optJSONObject("retweeted_status"));
    status.reposts_count = jsonObject.optInt("reposts_count");
    status.comments_count = jsonObject.optInt("comments_count");
    status.attitudes_count = jsonObject.optInt("attitudes_count");
    status.mlevel = jsonObject.optInt("mlevel", -1); // Have NOT supported
    status.visible = Visible.parse(jsonObject.optJSONObject("visible"));

    JSONArray picUrlsArray = jsonObject.optJSONArray("pic_urls");
    if (picUrlsArray != null && picUrlsArray.length() > 0) {
        int length = picUrlsArray.length();
        status.pic_urls = new ArrayList<String>(length);
        JSONObject tmpObject = null;
        for (int ix = 0; ix < length; ix++) {
            tmpObject = picUrlsArray.optJSONObject(ix);
            if (tmpObject != null) {
                status.pic_urls.add(tmpObject.optString("thumbnail_pic"));
            }
        }
    }

    //status.ad = jsonObject.optString("ad", "");

    return status;
}

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

public static List<SrnAction> createActions(Context mContext, CallbackContext callbackContext,
        RichNotificationOptions options) throws JSONException {
    ArrayList<SrnAction> actionsList = new ArrayList<SrnAction>();
    JSONArray actions = options.actions;
    if (actions == null)
        return null;

    SrnAction action = null;/*  ww  w .jav  a 2  s  . c  o  m*/
    for (int i = 0; i < actions.length(); i++) {
        JSONObject act = actions.optJSONObject(i);
        if (act == null)
            continue;

        String actionLabel = act.optString("actionLabel", EMPTY_STRING);
        if (actionLabel.isEmpty())
            continue;

        Bitmap actionIcon = getIconBitmap(mContext, "file://" + act.optString("actionIcon"));
        SrnImageAsset actionImg = new SrnImageAsset(mContext, actionLabel, actionIcon);

        int actionType = act.optInt("type");
        switch (actionType) {

        case ACTION_TYPE_CALL:
            SrnRemoteBuiltInAction call = new SrnRemoteBuiltInAction(actionLabel, OperationType.CALL);
            call.setData(Uri.parse(act.optString("dest")));
            action = call;
            break;
        case ACTION_TYPE_SMS:
            SrnRemoteBuiltInAction sms = new SrnRemoteBuiltInAction(actionLabel, OperationType.SMS);
            sms.setData(Uri.fromParts("sms", act.optString("dest"), null));
            action = sms;
            break;
        case ACTION_TYPE_EMAIL:
            Log.d(TAG, "Email to: '" + act.optString("dest") + "'");
            Log.d(TAG, "Subject: '" + act.optString("subject") + "'");
            Log.d(TAG, "Body: '" + act.optString("body") + "'");

            SrnHostAction email = new SrnHostAction(actionLabel);
            Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
            String uriText = "mailto:" + act.optString("dest") + "?subject="
                    + Uri.encode(act.optString("subject")) + "&body=" + Uri.encode(act.optString("body"));
            Uri uri = Uri.parse(uriText);
            emailIntent.setData(uri);
            email.setCallbackIntent(CallbackIntent.getActivityCallback(emailIntent));
            email.setToast(act.optString("toast"));
            email.setIcon(actionImg);
            action = email;
            break;
        case ACTION_TYPE_VIEW:
            SrnHostAction view = new SrnHostAction(actionLabel);
            Intent viewIntent = new Intent(Intent.ACTION_VIEW);
            String urlText = act.optString("dest");
            Uri url = Uri.parse(urlText);
            viewIntent.setData(url);
            view.setCallbackIntent(CallbackIntent.getActivityCallback(viewIntent));
            view.setToast(act.optString("toast"));
            view.setIcon(actionImg);
            action = view;
            break;
        case ACTION_TYPE_INPUT_KEYBOARD:
        case ACTION_TYPE_INPUT_SINGLE_SELECT:
        case ACTION_TYPE_INPUT_MULTI_SELECT:
            SrnRemoteInputAction input = getRemoteInputAction(mContext, act);
            if (input == null) {
                continue;
            }

            Intent inputIntent = new Intent("com.samsung.cordova.richnotification.remote_input_receiver");
            inputIntent.putExtra("callbackID", callbackContext.getCallbackId());
            String actionID = act.optString("actionID", EMPTY_STRING);
            if (actionID.isEmpty()) {
                continue;
            } else {
                inputIntent.putExtra("actionID", actionID);
            }
            input.setCallbackIntent(CallbackIntent.getBroadcastCallback(inputIntent));
            input.setIcon(actionImg);
            action = input;
            break;
        default:
            Log.e(TAG, "Invalid action type: " + actionType);
            continue;
        }

        Log.d(TAG, "Action type created: " + actionType);
        actionsList.add(action);
    }

    return actionsList;
}

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  w ww  .  j av a2 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;
}