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, int defaultValue) 

Source Link

Document

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

Usage

From source file:com.funzio.pure2D.particles.nova.vo.MotionTrailVO.java

public MotionTrailVO(final JSONObject json) throws JSONException {
    name = json.optString("name");
    type = json.optString("type", SHAPE);
    num_points = json.optInt("num_points", 10);
}

From source file:org.akop.ararat.io.WSJFormatter.java

private static void readClues(Crossword.Builder builder, JSONObject copyObj, Grid grid) {
    JSONArray cluesArray = copyObj.optJSONArray("clues");
    if (cluesArray == null) {
        throw new FormatException("Missing 'data.copy.clues[]'");
    } else if (cluesArray.length() != 2) {
        throw new FormatException("Unexpected clues length of '" + cluesArray.length() + "'");
    }/*  w w  w  .ja  v  a2  s. com*/

    JSONArray wordsArray = copyObj.optJSONArray("words");
    if (wordsArray == null) {
        throw new FormatException("Missing 'data.copy.words[]'");
    }

    // We'll need this to assign x/y locations to each clue
    SparseArray<Word> words = new SparseArray<>();
    for (int i = 0, n = wordsArray.length(); i < n; i++) {
        Word word;
        try {
            word = Word.parseJSON(wordsArray.optJSONObject(i));
        } catch (Exception e) {
            throw new FormatException("Error parsing 'data.copy.words[" + i + "]'", e);
        }

        words.put(word.mId, word);
    }

    // Go through the list of clues
    for (int i = 0, n = cluesArray.length(); i < n; i++) {
        JSONObject clueObj = cluesArray.optJSONObject(i);
        if (clueObj == null) {
            throw new FormatException("'data.copy.clues[" + i + "]' is null");
        }

        JSONArray subcluesArray = clueObj.optJSONArray("clues");
        if (subcluesArray == null) {
            throw new FormatException("Missing 'data.copy.clues[" + i + "].clues'");
        }

        int dir;
        String clueDir = clueObj.optString("title");
        if ("Across".equalsIgnoreCase(clueDir)) {
            dir = Crossword.Word.DIR_ACROSS;
        } else if ("Down".equalsIgnoreCase(clueDir)) {
            dir = Crossword.Word.DIR_DOWN;
        } else {
            throw new FormatException("Invalid direction: '" + clueDir + "'");
        }

        for (int j = 0, o = subcluesArray.length(); j < o; j++) {
            JSONObject subclue = subcluesArray.optJSONObject(j);
            Word word = words.get(subclue.optInt("word", -1));
            if (word == null) {
                throw new FormatException(
                        "No matching word for clue at 'data.copy.clues[" + i + "].clues[" + j + "].word'");
            }

            Crossword.Word.Builder wb = new Crossword.Word.Builder().setDirection(dir)
                    .setHint(subclue.optString("clue")).setNumber(subclue.optInt("number"))
                    .setStartColumn(word.mCol).setStartRow(word.mRow);

            if (dir == Crossword.Word.DIR_ACROSS) {
                for (int k = word.mCol, l = 0; l < word.mLen; k++, l++) {
                    Square square = grid.mSquares[word.mRow][k];
                    if (square == null) {
                        throw new FormatException(
                                "grid[" + word.mRow + "][" + k + "] is null (it shouldn't be)");
                    }
                    wb.addCell(square.mChar, 0);
                }
            } else {
                for (int k = word.mRow, l = 0; l < word.mLen; k++, l++) {
                    Square square = grid.mSquares[k][word.mCol];
                    if (square == null) {
                        throw new FormatException(
                                "grid[" + k + "][" + word.mCol + "] is null (it shouldn't be)");
                    }
                    wb.addCell(square.mChar, 0);
                }
            }

            builder.addWord(wb.build());
        }
    }
}

From source file:com.trk.aboutme.facebook.FacebookRequestError.java

static FacebookRequestError checkResponseAndCreateError(JSONObject singleResult, Object batchResult,
        HttpURLConnection connection) {
    try {//  w w  w.  j  a v  a2  s.c  o  m
        if (singleResult.has(CODE_KEY)) {
            int responseCode = singleResult.getInt(CODE_KEY);
            Object body = Utility.getStringPropertyAsJSON(singleResult, BODY_KEY,
                    Response.NON_JSON_RESPONSE_PROPERTY);

            if (body != null && body instanceof JSONObject) {
                JSONObject jsonBody = (JSONObject) body;
                // Does this response represent an error from the service? We might get either an "error"
                // with several sub-properties, or else one or more top-level fields containing error info.
                String errorType = null;
                String errorMessage = null;
                int errorCode = INVALID_ERROR_CODE;
                int errorSubCode = INVALID_ERROR_CODE;

                boolean hasError = false;
                if (jsonBody.has(ERROR_KEY)) {
                    // We assume the error object is correctly formatted.
                    JSONObject error = (JSONObject) Utility.getStringPropertyAsJSON(jsonBody, ERROR_KEY, null);

                    errorType = error.optString(ERROR_TYPE_FIELD_KEY, null);
                    errorMessage = error.optString(ERROR_MESSAGE_FIELD_KEY, null);
                    errorCode = error.optInt(ERROR_CODE_FIELD_KEY, INVALID_ERROR_CODE);
                    errorSubCode = error.optInt(ERROR_SUB_CODE_KEY, INVALID_ERROR_CODE);
                    hasError = true;
                } else if (jsonBody.has(ERROR_CODE_KEY) || jsonBody.has(ERROR_MSG_KEY)
                        || jsonBody.has(ERROR_REASON_KEY)) {
                    errorType = jsonBody.optString(ERROR_REASON_KEY, null);
                    errorMessage = jsonBody.optString(ERROR_MSG_KEY, null);
                    errorCode = jsonBody.optInt(ERROR_CODE_KEY, INVALID_ERROR_CODE);
                    errorSubCode = jsonBody.optInt(ERROR_SUB_CODE_KEY, INVALID_ERROR_CODE);
                    hasError = true;
                }

                if (hasError) {
                    return new FacebookRequestError(responseCode, errorCode, errorSubCode, errorType,
                            errorMessage, jsonBody, singleResult, batchResult, connection);
                }
            }

            // If we didn't get error details, but we did get a failure response code, report it.
            if (!HTTP_RANGE_SUCCESS.contains(responseCode)) {
                return new FacebookRequestError(responseCode, INVALID_ERROR_CODE, INVALID_ERROR_CODE, null,
                        null,
                        singleResult.has(BODY_KEY) ? (JSONObject) Utility.getStringPropertyAsJSON(singleResult,
                                BODY_KEY, Response.NON_JSON_RESPONSE_PROPERTY) : null,
                        singleResult, batchResult, connection);
            }
        }
    } catch (JSONException e) {
        // defer the throwing of a JSONException to the graph object proxy
    }
    return null;
}

From source file:com.phelps.liteweibo.model.weibo.CommentList.java

public static CommentList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }/*from   w  w w  .j  a va 2s.c o  m*/

    CommentList comments = new CommentList();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        comments.previous_cursor = jsonObject.optString("previous_cursor", "0");
        comments.next_cursor = jsonObject.optString("next_cursor", "0");
        comments.total_number = jsonObject.optInt("total_number", 0);

        JSONArray jsonArray = jsonObject.optJSONArray("comments");
        if (jsonArray != null && jsonArray.length() > 0) {
            int length = jsonArray.length();
            comments.commentList = new ArrayList<Comment>(length);
            for (int ix = 0; ix < length; ix++) {
                comments.commentList.add(Comment.parse(jsonArray.optJSONObject(ix)));
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return comments;
}

From source file:org.privatenotes.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"));
    lastSyncRevision = json.optInt("last-sync-revision", -1);
    setXmlContent(json.optString("note-content"));
    JSONArray jtags = json.optJSONArray("tags");
    String tag;//from www .java 2 s  .  c  om
    tags = new String();
    if (jtags != null) {
        for (int i = 0; i < jtags.length(); i++) {
            tag = jtags.optString(i);
            tags += tag + ",";
        }
    }

    // encryption/decryption
    if (json.optString("encrypted") != null) {
        //<encrypted>
        setEncrypted(json.optString("encrypted").toLowerCase().trim().equals("true"));
    }
    //<encryptedAlgorithm>
    setEncryptedAlgorithm(json.optString("encryptedAlgorithm"));
}

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

private static LikeActionController deserializeFromJson(String controllerJsonString) {
    LikeActionController controller;// w  w  w.  j av a2  s. c  o  m

    try {
        JSONObject controllerJson = new JSONObject(controllerJsonString);
        int version = controllerJson.optInt(JSON_INT_VERSION_KEY, -1);
        if (version != LIKE_ACTION_CONTROLLER_VERSION) {
            // Don't attempt to deserialize a controller that might be serialized differently than expected.
            return null;
        }

        controller = new LikeActionController(Session.getActiveSession(),
                controllerJson.getString(JSON_STRING_OBJECT_ID_KEY));

        // Make sure to default to null and not empty string, to keep the logic elsewhere functioning properly.
        controller.likeCountStringWithLike = controllerJson.optString(JSON_STRING_LIKE_COUNT_WITH_LIKE_KEY,
                null);
        controller.likeCountStringWithoutLike = controllerJson
                .optString(JSON_STRING_LIKE_COUNT_WITHOUT_LIKE_KEY, null);
        controller.socialSentenceWithLike = controllerJson.optString(JSON_STRING_SOCIAL_SENTENCE_WITH_LIKE_KEY,
                null);
        controller.socialSentenceWithoutLike = controllerJson
                .optString(JSON_STRING_SOCIAL_SENTENCE_WITHOUT_LIKE_KEY, null);
        controller.isObjectLiked = controllerJson.optBoolean(JSON_BOOL_IS_OBJECT_LIKED_KEY);
        controller.unlikeToken = controllerJson.optString(JSON_STRING_UNLIKE_TOKEN_KEY, null);
        String pendingCallIdString = controllerJson.optString(JSON_STRING_PENDING_CALL_ID_KEY, null);
        if (!Utility.isNullOrEmpty(pendingCallIdString)) {
            controller.pendingCallId = UUID.fromString(pendingCallIdString);
        }

        JSONObject analyticsJSON = controllerJson.optJSONObject(JSON_BUNDLE_PENDING_CALL_ANALYTICS_BUNDLE);
        if (analyticsJSON != null) {
            controller.pendingCallAnalyticsBundle = BundleJSONConverter.convertToBundle(analyticsJSON);
        }
    } catch (JSONException e) {
        Log.e(TAG, "Unable to deserialize controller from JSON", e);
        controller = null;
    }

    return controller;
}

From source file:net.zorgblub.typhon.dto.PageOffsets.java

public static PageOffsets fromJSON(String json) throws JSONException {
    JSONObject offsetsObject = new JSONObject(json);
    PageOffsets result = new PageOffsets();

    result.fontFamily = offsetsObject.getString(Fields.fontFamily.name());
    result.fontSize = offsetsObject.getInt(Fields.fontSize.name());
    result.vMargin = offsetsObject.getInt(Fields.vMargin.name());
    result.hMargin = offsetsObject.getInt(Fields.hMargin.name());
    result.lineSpacing = offsetsObject.getInt(Fields.lineSpacing.name());
    result.fullScreen = offsetsObject.getBoolean(Fields.fullScreen.name());
    result.algorithmVersion = offsetsObject.optInt(Fields.algorithmVersion.name(), -1);
    result.allowStyling = offsetsObject.optBoolean(Fields.allowStyling.name(), true);

    result.offsets = readOffsets(offsetsObject.getJSONArray(Fields.offsets.name()));

    return result;
}

From source file:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java

/** Create a task container for the given RtmTaskSeries
 * @throws JSONException/*  w  ww. j av a2  s  . com*/
 * @throws IOException
 * @throws ApiServiceException */
private OpencrxTaskContainer parseRemoteTask(JSONObject remoteTask)
        throws JSONException, ApiServiceException, IOException {

    String resourceId = Preferences.getStringValue(OpencrxUtilities.PREF_RESOURCE_ID);

    String crxId = remoteTask.getString("repeating_value");

    JSONArray labels = invoker.resourcesShowForTask(crxId);

    int secondsSpentOnTask = invoker.getSecondsSpentOnTask(crxId, resourceId);

    Task task = new Task();
    ArrayList<Metadata> metadata = new ArrayList<Metadata>();

    if (remoteTask.has("task"))
        remoteTask = remoteTask.getJSONObject("task");

    task.setValue(Task.TITLE, ApiUtilities.decode(remoteTask.getString("title")));
    task.setValue(Task.NOTES, remoteTask.getString("detailedDescription"));
    task.setValue(Task.CREATION_DATE,
            ApiUtilities.producteevToUnixTime(remoteTask.getString("time_created"), 0));
    task.setValue(Task.COMPLETION_DATE, remoteTask.getInt("status") == 1 ? DateUtilities.now() : 0);
    task.setValue(Task.DELETION_DATE, remoteTask.getInt("deleted") == 1 ? DateUtilities.now() : 0);
    task.setValue(Task.ELAPSED_SECONDS, secondsSpentOnTask);
    task.setValue(Task.MODIFICATION_DATE, remoteTask.getLong("modifiedAt"));

    long dueDate = ApiUtilities.producteevToUnixTime(remoteTask.getString("deadline"), 0);
    if (remoteTask.optInt("all_day", 0) == 1)
        task.setValue(Task.DUE_DATE, Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, dueDate));
    else
        task.setValue(Task.DUE_DATE, Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, dueDate));
    task.setValue(Task.IMPORTANCE, 5 - remoteTask.getInt("star"));

    for (int i = 0; i < labels.length(); i++) {
        JSONObject label = labels.getJSONObject(i);

        Metadata tagData = new Metadata();
        tagData.setValue(Metadata.KEY, OpencrxDataService.TAG_KEY);
        tagData.setValue(OpencrxDataService.TAG, label.getString("name"));
        metadata.add(tagData);
    }

    OpencrxTaskContainer container = new OpencrxTaskContainer(task, metadata, remoteTask);

    return container;
}

From source file:org.restcomm.app.utillib.Reporters.WebReporter.WebReporter.java

/**
 * Sends the registration request, receives the request and parses the response back
 *//*from  w  w  w. j a v  a2s .  c  o  m*/
public void authorizeDevice(DeviceInfo device, String email, String password, boolean bFailover)
        throws LibException {
    String host = mHost;
    {
        SharedPreferences preferenceSettings = PreferenceKeys.getSecurePreferences(mContext);
        preferenceSettings.edit().putString(PreferenceKeys.User.USER_EMAIL, email).commit();
        preferenceSettings.edit().putString(PreferenceKeys.Miscellaneous.KEY_GCM_REG_ID, "").commit();

        try {

            HttpURLConnection connection = RegistrationRequest.POSTConnection(host, device, email, password,
                    true);
            //verifyResponse throws an MMCException
            if (verifyConnectionResponse(connection)) {

                String contents = readString(connection); //getResponseString(response);
                JSONObject json = new JSONObject(contents);
                mApiKey = json.optString(JSON_API_KEY, "");

                int dormant = json.optInt("dormant", 0);
                int userID = json.optInt(USER_ID_KEY, 0);
                if (mApiKey.length() > 0) {
                    //SharedPreferences preferenceSettings = PreferenceManager.getDefaultSharedPreferences(mContext);
                    preferenceSettings.edit().putString(PreferenceKeys.User.APIKEY, mApiKey).commit();
                    // Also save email for this version so it can be copied to the contact email setting for email raw data
                    preferenceSettings.edit().putString(PreferenceKeys.User.USER_EMAIL, email).commit();
                    preferenceSettings.edit().putString(PreferenceKeys.User.CONTACT_EMAIL, email).commit();
                    PreferenceManager.getDefaultSharedPreferences(mContext).edit()
                            .putString(PreferenceKeys.User.CONTACT_EMAIL, email).commit();
                    preferenceSettings.edit().putBoolean(PreferenceKeys.Miscellaneous.SIGNED_OUT, false)
                            .commit();
                    PreferenceManager.getDefaultSharedPreferences(mContext).edit()
                            .putInt(PreferenceKeys.Miscellaneous.USAGE_DORMANT_MODE, (int) dormant).commit();

                } else {
                    LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "authorizeDevice", "api key is empty");
                    throw new LibException("api key was empty");
                }
                if (userID > 0) {
                    preferenceSettings.edit().putInt(PreferenceKeys.User.USER_ID, userID).commit();
                    LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "authorizeDevice", "userID=" + userID);
                } else {
                    LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "authorizeDevice", "user id is empty");
                }
            }
        } catch (IOException e) {
            //Just log the exception for now
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "authorizeDevice", "fail to send authorization",
                    e);
            //            if (bFailover)
            //               AuthorizeWindows (email);
            throw new LibException(e);
        } catch (JSONException e) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "authorizeDevice",
                    "fail to recieve authorization", e);
            //            if (bFailover)
            //               AuthorizeWindows (email);
            throw new LibException(e);
        } catch (Exception e) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "authorizeDevice",
                    "fail to recieve authorization", e);
            //            if (bFailover)
            //               AuthorizeWindows (email);
            throw new LibException(e);
        }

    }
}

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

/**
 * Fills list according with data in {@code from}.
 * @param from an object that represents a list adopted in accordance with VK API format. You can use null.
 * @param creator interface implementation to parse objects.
 *//* w  ww .j a v  a  2s .com*/
public void fill(JSONObject from, Parser<? extends T> creator) {
    if (from != null) {
        fill(from.optJSONArray("items"), creator);
        count = from.optInt("count", count);
    }
}