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.google.blockly.model.BlockFactory.java

/**
 * Generate a {@link Block} from JSON, including all inputs and fields within the block.
 *
 * @param type The type id of the block.
 * @param json The JSON to generate the block from.
 *
 * @return The generated Block./*from  w  w  w . java  2s. c o m*/
 * @throws BlockLoadingException if the json is malformed.
 */
public Block fromJson(String type, JSONObject json) throws BlockLoadingException {
    if (TextUtils.isEmpty(type)) {
        throw new IllegalArgumentException("Block type may not be null or empty.");
    }
    if (json == null) {
        throw new IllegalArgumentException("Json may not be null.");
    }
    Block.Builder builder = new Block.Builder(type);

    if (json.has("output") && json.has("previousStatement")) {
        throw new BlockLoadingException("Block cannot have both an output and a previous statement.");
    }

    // Parse any connections that are present.
    if (json.has("output")) {
        String[] checks = Input.getChecksFromJson(json, "output");
        Connection output = new Connection(Connection.CONNECTION_TYPE_OUTPUT, checks);
        builder.setOutput(output);
    } else if (json.has("previousStatement")) {
        String[] checks = Input.getChecksFromJson(json, "previousStatement");
        Connection previous = new Connection(Connection.CONNECTION_TYPE_PREVIOUS, checks);
        builder.setPrevious(previous);
    }
    // A block can have either an output connection or previous connection, but it can always
    // have a next connection.
    if (json.has("nextStatement")) {
        String[] checks = Input.getChecksFromJson(json, "nextStatement");
        Connection next = new Connection(Connection.CONNECTION_TYPE_NEXT, checks);
        builder.setNext(next);
    }
    if (json.has("inputsInline")) {
        try {
            builder.setInputsInline(json.getBoolean("inputsInline"));
        } catch (JSONException e) {
            // Do nothing and it will remain false.
        }
    }

    int blockColor = ColorUtils.DEFAULT_BLOCK_COLOR;
    if (json.has("colour")) {
        try {
            String colourString = json.getString("colour");
            blockColor = ColorUtils.parseColor(colourString, TEMP_IO_THREAD_FLOAT_ARRAY,
                    ColorUtils.DEFAULT_BLOCK_COLOR);
        } catch (JSONException e) {
            // Won't get here. Checked above.
        }
    }
    builder.setColor(blockColor);

    ArrayList<Input> inputs = new ArrayList<>();
    ArrayList<Field> fields = new ArrayList<>();
    for (int i = 0;; i++) {
        String messageKey = "message" + i;
        String argsKey = "args" + i;
        String lastDummyAlignKey = "lastDummyAlign" + i;
        if (!json.has(messageKey)) {
            break;
        }
        String message = json.optString(messageKey);
        JSONArray args = json.optJSONArray(argsKey);
        if (args == null) {
            // If there's no args for this message use an empty array.
            args = new JSONArray();
        }

        if (message.matches("^%[a-zA-Z][a-zA-Z_0-9]*$")) {
            // TODO(#83): load the message from resources.
        }
        // Split on all argument indices of the form "%N" where N is a number from 1 to
        // the number of args without removing them.
        List<String> tokens = Block.tokenizeMessage(message);
        int indexCount = 0;
        // Indices start at 1, make the array 1 bigger so we don't have to offset things
        boolean[] seenIndices = new boolean[args.length() + 1];

        for (String token : tokens) {
            // Check if this token is an argument index of the form "%N"
            if (token.matches("^%\\d+$")) {
                int index = Integer.parseInt(token.substring(1));
                if (index < 1 || index > args.length()) {
                    throw new BlockLoadingException("Message index " + index + " is out of range.");
                }
                if (seenIndices[index]) {
                    throw new BlockLoadingException(("Message index " + index + " is duplicated"));
                }
                seenIndices[index] = true;

                JSONObject element;
                try {
                    element = args.getJSONObject(index - 1);
                } catch (JSONException e) {
                    throw new BlockLoadingException("Error reading arg %" + index, e);
                }
                while (element != null) {
                    String elementType = element.optString("type");
                    if (TextUtils.isEmpty(elementType)) {
                        throw new BlockLoadingException("No type for arg %" + index);
                    }

                    if (Field.isFieldType(elementType)) {
                        fields.add(loadFieldFromJson(type, element));
                        break;
                    } else if (Input.isInputType(elementType)) {
                        Input input = Input.fromJson(element);
                        input.addAll(fields);
                        fields.clear();
                        inputs.add(input);
                        break;
                    } else {
                        // Try getting the fallback block if it exists
                        Log.w(TAG, "Unknown element type: " + elementType);
                        element = element.optJSONObject("alt");
                    }
                }
            } else {
                token = token.replace("%%", "%").trim();
                if (!TextUtils.isEmpty(token)) {
                    fields.add(new FieldLabel(null, token));
                }
            }
        }

        // Verify every argument was used
        for (int j = 1; j < seenIndices.length; j++) {
            if (!seenIndices[j]) {
                throw new BlockLoadingException("Argument " + j + " was never used.");
            }
        }
        // If there were leftover fields we need to add a dummy input to hold them.
        if (fields.size() != 0) {
            String align = json.optString(lastDummyAlignKey, Input.ALIGN_LEFT_STRING);
            Input input = new Input.InputDummy(null, align);
            input.addAll(fields);
            inputs.add(input);
            fields.clear();
        }
    }

    builder.setInputs(inputs);
    return builder.build();
}

From source file:com.jsonstore.api.JSONStoreChangeOptions.java

public JSONStoreChangeOptions(JSONObject js_options) throws JSONException {
    this();/* w  ww  .j av  a2 s .  c  o  m*/
    if (js_options == null)
        return;

    if (js_options.has(ADD_NEW_KEY)) {
        setAddNew(js_options.getBoolean(ADD_NEW_KEY));
    }

    if (js_options.has(MARK_DIRTY_KEY)) {
        setMarkDirty(js_options.getBoolean(MARK_DIRTY_KEY));
    }

    if (js_options.has(REPLACE_CRITERIA_KEY)) {
        JSONArray replaceCrit = js_options.optJSONArray(REPLACE_CRITERIA_KEY);
        if (replaceCrit != null) {
            for (int i = 0; i < replaceCrit.length(); i++) {
                addSearchFieldToCriteria(replaceCrit.getString(i));
            }
        }
    }

}

From source file:org.smilec.smile.bu.json.ResultsJSONParser.java

public static final Results process(JSONObject object) {

    int winnerScore = object.optInt(WINNER_SCORE);
    float winnerRating = object.optLong(WINNER_RATING);

    JSONArray optJSONArray = object.optJSONArray(BEST_SCORED_STUDENT_NAMES);
    JSONArray bestScoredStudentNames = optJSONArray == null ? new JSONArray() : optJSONArray;

    JSONArray optJSONArray2 = object.optJSONArray(BEST_RATED_QUESTION_STUDENT_NAMES);
    JSONArray bestRatedQuestionStudentNames = optJSONArray2 == null ? new JSONArray() : optJSONArray2;

    JSONArray optJSONArray3 = object.optJSONArray(RIGHT_ANSWERS);
    JSONArray rightAnswers = optJSONArray3 == null ? new JSONArray() : optJSONArray3;

    int numberOfQuestions = object.optInt(NUMBER_OF_QUESTIONS);

    JSONArray optJSONArray4 = object.optJSONArray(AVERAGE_RATINGS);
    JSONArray averageRatings = optJSONArray4 == null ? new JSONArray() : optJSONArray4;

    JSONArray optJSONArray5 = object.optJSONArray(QUESTIONS_CORRECT_PERCENTAGE);
    JSONArray questionsCorrectPercentage = optJSONArray5 == null ? new JSONArray() : optJSONArray5;

    Results results = new Results(winnerScore, winnerRating, bestScoredStudentNames,
            bestRatedQuestionStudentNames, numberOfQuestions, rightAnswers, averageRatings,
            questionsCorrectPercentage);

    return results;

}

From source file:org.eclipse.orion.server.tests.servlets.workspace.WorkspaceServiceTest.java

@Test
public void testCreateProject() throws Exception {
    //create workspace
    String workspaceName = WorkspaceServiceTest.class.getName() + "#testCreateProject";
    URI workspaceLocation = createWorkspace(workspaceName);

    //create a project
    String projectName = "My Project";
    WebRequest request = getCreateProjectRequest(workspaceLocation, projectName, null);
    WebResponse response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    String locationHeader = response.getHeaderField(ProtocolConstants.HEADER_LOCATION);
    assertNotNull(locationHeader);/*from w  w  w  .j  ava 2s .  com*/

    JSONObject project = new JSONObject(response.getText());
    assertEquals(projectName, project.getString(ProtocolConstants.KEY_NAME));
    String projectId = project.optString(ProtocolConstants.KEY_ID, null);
    assertNotNull(projectId);

    //ensure project location = <workspace location>/project/<projectName>
    URI projectLocation = new URI(toAbsoluteURI(locationHeader));
    URI relative = workspaceLocation.relativize(projectLocation);
    IPath projectPath = new Path(relative.getPath());
    assertEquals(2, projectPath.segmentCount());
    assertEquals("project", projectPath.segment(0));
    assertEquals(projectName, projectPath.segment(1));

    //ensure project appears in the workspace metadata
    request = new GetMethodWebRequest(addSchemeHostPort(workspaceLocation).toString());
    setAuthentication(request);
    response = webConversation.getResponse(request);
    JSONObject workspace = new JSONObject(response.getText());
    assertNotNull(workspace);
    JSONArray projects = workspace.getJSONArray(ProtocolConstants.KEY_PROJECTS);
    assertEquals(1, projects.length());
    JSONObject createdProject = projects.getJSONObject(0);
    assertEquals(projectId, createdProject.get(ProtocolConstants.KEY_ID));
    assertNotNull(createdProject.optString(ProtocolConstants.KEY_LOCATION, null));

    //check for children element to conform to structure of file API
    JSONArray children = workspace.optJSONArray(ProtocolConstants.KEY_CHILDREN);
    assertNotNull(children);
    assertEquals(1, children.length());
    JSONObject child = children.getJSONObject(0);
    assertEquals(projectName, child.optString(ProtocolConstants.KEY_NAME));
    assertEquals("true", child.optString(ProtocolConstants.KEY_DIRECTORY));
    String contentLocation = child.optString(ProtocolConstants.KEY_LOCATION);
    assertNotNull(contentLocation);

    //ensure project content exists
    if (OrionConfiguration.getMetaStore() instanceof SimpleMetaStore) {
        // simple metastore, projects not in the same simple location anymore, so do not check
    } else {
        // legacy metastore, use what was in the original test
        IFileStore projectStore = EFS.getStore(makeLocalPathAbsolute(projectId));
        assertTrue(projectStore.fetchInfo().exists());
    }

    //add a file in the project
    String fileName = "file.txt";
    request = getPostFilesRequest(toAbsoluteURI(contentLocation), getNewFileJSON(fileName).toString(),
            fileName);
    response = webConversation.getResponse(request);
    assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode());
    assertEquals("Response should contain file metadata in JSON, but was " + response.getText(),
            "application/json", response.getContentType());
    JSONObject responseObject = new JSONObject(response.getText());
    assertNotNull("No file information in response", responseObject);
    checkFileMetadata(responseObject, fileName, null, null, null, null, null, null, null, projectName);
}

From source file:org.eclipse.orion.server.tests.servlets.workspace.WorkspaceServiceTest.java

@Test
public void testGetWorkspaces() throws IOException, SAXException, JSONException {
    WebRequest request = new GetMethodWebRequest(SERVER_LOCATION + "/workspace");
    setAuthentication(request);/*from ww  w  . j  ava2  s .  c o m*/
    WebResponse response = webConversation.getResponse(request);

    //before creating an workspaces we should get an empty list
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertEquals("application/json", response.getContentType());
    JSONObject responseObject = new JSONObject(response.getText());
    assertNotNull("No workspace information in response", responseObject);
    String userId = responseObject.optString(ProtocolConstants.KEY_ID, null);
    assertNotNull(userId);
    assertEquals(testUserId, responseObject.optString("UserName"));
    JSONArray workspaces = responseObject.optJSONArray("Workspaces");
    assertNotNull(workspaces);
    assertEquals(0, workspaces.length());

    //now create a workspace
    String workspaceName = WorkspaceServiceTest.class.getName() + "#testGetWorkspaces";
    response = basicCreateWorkspace(workspaceName);
    responseObject = new JSONObject(response.getText());
    String workspaceId = responseObject.optString(ProtocolConstants.KEY_ID, null);
    assertNotNull(workspaceId);

    //get the workspace list again
    request = new GetMethodWebRequest(SERVER_LOCATION + "/workspace");
    setAuthentication(request);
    response = webConversation.getResponse(request);

    //assert that the workspace we created is found by a subsequent GET
    assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode());
    assertEquals("application/json", response.getContentType());
    responseObject = new JSONObject(response.getText());
    assertNotNull("No workspace information in response", responseObject);
    assertEquals(userId, responseObject.optString(ProtocolConstants.KEY_ID));
    assertEquals(testUserId, responseObject.optString("UserName"));
    workspaces = responseObject.optJSONArray("Workspaces");
    assertNotNull(workspaces);
    assertEquals(1, workspaces.length());
    JSONObject workspace = (JSONObject) workspaces.get(0);
    assertEquals(workspaceId, workspace.optString(ProtocolConstants.KEY_ID));
    assertNotNull(workspace.optString(ProtocolConstants.KEY_LOCATION, null));
}

From source file:cgeo.geocaching.connector.oc.OkapiClient.java

private static Geocache parseCache(final JSONObject response) {
    final Geocache cache = new Geocache();
    cache.setReliableLatLon(true);/*from w  ww  . j  ava  2s  .  c o  m*/
    try {

        parseCoreCache(response, cache);

        // not used: url
        final JSONObject owner = response.getJSONObject(CACHE_OWNER);
        cache.setOwnerDisplayName(parseUser(owner));

        cache.getLogCounts().put(LogType.FOUND_IT, response.getInt(CACHE_FOUNDS));
        cache.getLogCounts().put(LogType.DIDNT_FIND_IT, response.getInt(CACHE_NOTFOUNDS));

        if (!response.isNull(CACHE_RATING)) {
            cache.setRating((float) response.getDouble(CACHE_RATING));
        }
        cache.setVotes(response.getInt(CACHE_VOTES));

        cache.setFavoritePoints(response.getInt(CACHE_RECOMMENDATIONS));
        // not used: req_password
        // Prepend gc-link to description if available
        final StringBuilder description = new StringBuilder(500);
        if (!response.isNull("gc_code")) {
            final String gccode = response.getString("gc_code");
            description
                    .append(CgeoApplication.getInstance().getResources().getString(R.string.cache_listed_on,
                            GCConnector.getInstance().getName()))
                    .append(": <a href=\"http://coord.info/").append(gccode).append("\">").append(gccode)
                    .append("</a><br /><br />");
        }
        description.append(response.getString(CACHE_DESCRIPTION));
        cache.setDescription(description.toString());

        // currently the hint is delivered as HTML (contrary to OKAPI documentation), so we can store it directly
        cache.setHint(response.getString(CACHE_HINT));
        // not used: hints

        final JSONArray images = response.getJSONArray(CACHE_IMAGES);
        if (images != null) {
            for (int i = 0; i < images.length(); i++) {
                final JSONObject imageResponse = images.getJSONObject(i);
                final String title = imageResponse.getString(CACHE_IMAGE_CAPTION);
                final String url = absoluteUrl(imageResponse.getString(CACHE_IMAGE_URL), cache.getGeocode());
                // all images are added as spoiler images, although OKAPI has spoiler and non spoiler images
                cache.addSpoiler(new Image(url, title));
            }
        }

        cache.setAttributes(parseAttributes(response.getJSONArray(CACHE_ATTRNAMES),
                response.optJSONArray(CACHE_ATTR_ACODES)));
        cache.setLogs(parseLogs(response.getJSONArray(CACHE_LATEST_LOGS)));
        //TODO: Store license per cache
        //cache.setLicense(response.getString("attribution_note"));
        cache.setWaypoints(parseWaypoints(response.getJSONArray(CACHE_WPTS)), false);
        if (!response.isNull(CACHE_IS_WATCHED)) {
            cache.setOnWatchlist(response.getBoolean(CACHE_IS_WATCHED));
        }
        if (!response.isNull(CACHE_MY_NOTES)) {
            cache.setPersonalNote(response.getString(CACHE_MY_NOTES));
            cache.parseWaypointsFromNote();
        }
        cache.setLogPasswordRequired(response.getBoolean(CACHE_REQ_PASSWORD));

        cache.setDetailedUpdatedNow();
        // save full detailed caches
        DataStore.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB));
    } catch (final JSONException e) {
        Log.e("OkapiClient.parseCache", e);
    }
    return cache;
}

From source file:org.catnut.service.UpgradeService.java

private void checkout() throws Exception {
    URL url = new URL(METADATA_URL);
    InputStream inputStream = url.openStream();
    Scanner in = new Scanner(inputStream).useDelimiter("\\A");
    if (in.hasNext()) {
        JSONObject metadata = new JSONObject(in.next());
        PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
        if (info.versionCode < metadata.optInt(FIELD_VERSION_CODE)) {
            Notification.InboxStyle style = new Notification.InboxStyle(mBuilder);
            String size = metadata.optString("size");
            style.setBigContentTitle(getString(R.string.find_new_version, size));
            JSONArray messages = metadata.optJSONArray("messages");
            for (int i = 0; i < messages.length(); i++) {
                style.addLine(messages.optString(i));
            }/*from w ww. j  av  a2 s .c  om*/
            // download&upgrade intent
            Intent download = new Intent(this, UpgradeService.class);
            download.setAction(ACTION_DOWNLOAD);
            download.putExtra(DOWNLOAD_LINK, metadata.optString(DOWNLOAD_LINK));
            PendingIntent piDownload = PendingIntent.getService(this, 0, download, 0);
            mBuilder.addAction(R.drawable.ic_stat_download_dark, getString(R.string.down_load_and_upgrade),
                    piDownload);
            // dismiss notification
            Intent dismiss = new Intent(this, UpgradeService.class);
            dismiss.setAction(ACTION_DISMISS);
            PendingIntent piDismiss = PendingIntent.getService(this, 0, dismiss, 0);
            mBuilder.addAction(R.drawable.ic_stat_content_remove_dark, getString(R.string.not_upgrade_now),
                    piDismiss);
            // show it.
            mBuilder.setTicker(getString(R.string.find_new_version));
            mNotificationManager.notify(ID, mBuilder.setDefaults(Notification.DEFAULT_ALL).build());
        } else {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(UpgradeService.this, getString(R.string.already_updated), Toast.LENGTH_SHORT)
                            .show();
                }
            });
        }
    }
    in.close();
}

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

/**
 * Fills a Comment instance from JSONObject.
 *//*  w w w .  ja v a  2  s  .  c  o m*/
public VKApiComment parse(JSONObject from) throws JSONException {
    id = from.optInt("id");
    from_id = from.optInt("from_id");
    date = from.optLong("date");
    text = from.optString("text");
    reply_to_user = from.optInt("reply_to_user");
    reply_to_comment = from.optInt("reply_to_comment");
    attachments.fill(from.optJSONArray("attachments"));
    JSONObject likes = from.optJSONObject("likes");
    this.likes = ParseUtils.parseInt(likes, "count");
    this.user_likes = ParseUtils.parseBoolean(likes, "user_likes");
    this.can_like = ParseUtils.parseBoolean(likes, "can_like");
    return this;
}

From source file:com.norman0406.slimgress.API.Interface.GameBasket.java

public GameBasket(JSONObject json) throws JSONException {
    mPlayerEntity = null;/*from  w  ww .  j  a va  2s. c  o  m*/
    mGameEntities = new LinkedList<GameEntityBase>();
    mInventory = new LinkedList<ItemBase>();
    mDeletedEntityGuids = new LinkedList<String>();
    mEnergyGlobGuids = new LinkedList<XMParticle>();
    mPlayerDamages = new LinkedList<PlayerDamage>();
    mAPGains = new LinkedList<APGain>();

    processPlayerDamages(json.optJSONArray("playerDamages"));
    processPlayerEntity(json.optJSONArray("playerEntity"));
    processGameEntities(json.getJSONArray("gameEntities"));
    processAPGains(json.optJSONArray("apGains"));
    processLevelUp(json.optJSONObject("levelUp"));
    processInventory(json.getJSONArray("inventory"));
    processDeletedEntityGuids(json.getJSONArray("deletedEntityGuids"));
    processEnergyGlobGuids(json.optJSONArray("energyGlobGuids"), json.optString("energyGlobTimestamp"));
}

From source file:com.sina.weibo.sdk_lib.openapi.models.FavoriteList.java

public static FavoriteList parse(String jsonString) {
    if (TextUtils.isEmpty(jsonString)) {
        return null;
    }/*from  w w w .  ja v a2 s  .  co m*/

    FavoriteList favorites = new FavoriteList();
    try {
        JSONObject jsonObject = new JSONObject(jsonString);
        favorites.total_number = jsonObject.optInt("total_number", 0);

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

    return favorites;
}