Example usage for org.json JSONArray getJSONObject

List of usage examples for org.json JSONArray getJSONObject

Introduction

In this page you can find the example usage for org.json JSONArray getJSONObject.

Prototype

public JSONObject getJSONObject(int index) throws JSONException 

Source Link

Document

Get the JSONObject associated with an index.

Usage

From source file:net.mandaria.radioreddit.apis.RadioRedditAPI.java

public static RadioEpisode GetEpisodeVoteScore(Context context, RadioRedditApplication application,
        RadioEpisode radioepisode) {/*from w w  w. j a va2  s  . c  om*/
    try {
        // get vote score 
        String reddit_info_url = context.getString(R.string.reddit_link_by)
                + URLEncoder.encode(radioepisode.Reddit_url);

        String outputRedditInfo = "";
        boolean errorGettingRedditInfo = false;

        try {
            outputRedditInfo = HTTPUtil.get(context, reddit_info_url);
        } catch (Exception ex) {
            ex.printStackTrace();
            errorGettingRedditInfo = true;
            // For now, not used. It is acceptable to error out and not alert the user
            // radiosong.ErrorMessage = "Unable to connect to reddit";//context.getString(R.string.error_RadioRedditServerIsDownNotification);
        }

        if (!errorGettingRedditInfo && outputRedditInfo.length() > 0) {
            // Log.e("radio_reddit_test", "Length: " + outputRedditInfo.length());
            // Log.e("radio_reddit_test", "Value: " + outputRedditInfo); // TODO: sometimes the value contains "error: 404", need to check for that. (We can probably safely ignore this for now)
            JSONTokener reddit_info_tokener = new JSONTokener(outputRedditInfo);
            JSONObject reddit_info_json = new JSONObject(reddit_info_tokener);

            JSONObject data = reddit_info_json.getJSONObject("data");

            // default value of score
            String score = context.getString(R.string.vote_to_submit_song);
            String likes = "null";
            String name = "";

            JSONArray children_array = data.getJSONArray("children");

            // Song hasn't been submitted yet
            if (children_array.length() > 0) {
                JSONObject children = children_array.getJSONObject(0);

                JSONObject children_data = children.getJSONObject("data");
                score = children_data.getString("score");

                likes = children_data.getString("likes");
                name = children_data.getString("name");
            }

            radioepisode.Score = score;
            radioepisode.Likes = likes;
            radioepisode.Name = name;
        } else {
            radioepisode.Score = "?";
            radioepisode.Likes = "null";
            radioepisode.Name = "";
        }
    } catch (Exception ex) {
        // We fail to get the vote information...
        CustomExceptionHandler ceh = new CustomExceptionHandler(context);
        ceh.sendEmail(ex);

        ex.printStackTrace();
        // return error message??
        radioepisode.ErrorMessage = context.getString(R.string.error_GettingVoteInformation);
        //return radiosong;
    }

    return radioepisode;
}

From source file:to.networld.fbtosemweb.FacebookToSIOC.java

/**
 * TODO: If a link was posted, add also the link to the SIOC block.
 * @throws IOException//from  w  w  w . j a va 2s  .  c om
 * @throws JSONException
 */
public void createSIOC() throws IOException, JSONException {
    Element rootNode = this.rdfDocument.addElement(new QName("RDF", RDF_NS));
    rootNode.add(SIOC_NS);
    rootNode.add(DCT_NS);

    JSONArray wallEntries = this.object.getJSONArray("data");
    for (int count = 0; count < wallEntries.length(); count++) {
        JSONObject wallEntry = (JSONObject) wallEntries.get(count);
        Element siocPost = rootNode.addElement(new QName("Post", SIOC_NS)).addAttribute(
                new QName("about", RDF_NS), "http://graph.facebook.com/" + wallEntry.getString("id"));
        siocPost.addElement(new QName("content", SIOC_NS)).setText(wallEntry.getString("message"));
        String creatorID = wallEntry.getJSONObject("from").getString("id");
        siocPost.addElement(new QName("hasCreator", SIOC_NS)).addAttribute(new QName("resource", RDF_NS),
                "http://graph.facebook.com/" + creatorID);
        try {
            siocPost.addElement(new QName("created", SIOC_NS)).setText(wallEntry.getString("created_time"));
        } catch (JSONException e) {
        }
        try {
            siocPost.addElement(new QName("modified", SIOC_NS)).setText(wallEntry.getString("updated_time"));
        } catch (JSONException e) {
        }

        try {
            JSONArray comments = wallEntry.getJSONObject("comments").getJSONArray("data");
            for (int count1 = 0; count1 < comments.length(); count1++) {
                JSONObject comment = comments.getJSONObject(count1);
                Element replyNode = siocPost.addElement(new QName("has_reply", SIOC_NS));
                Element replyPost = replyNode.addElement(new QName("Post", SIOC_NS));
                replyPost.addAttribute(new QName("about", RDF_NS),
                        "http://graph.facebook.com/" + comment.getString("id"));
                replyPost.addElement(new QName("content", SIOC_NS)).setText(comment.getString("message"));
                String replierID = comment.getJSONObject("from").getString("id");
                replyPost.addElement(new QName("hasCreator", SIOC_NS))
                        .addAttribute(new QName("resource", RDF_NS), "http://graph.facebook.com/" + replierID);
                try {
                    replyPost.addElement(new QName("created", SIOC_NS))
                            .setText(comment.getString("created_time"));
                } catch (JSONException e) {
                }
                try {
                    replyPost.addElement(new QName("modified", SIOC_NS))
                            .setText(comment.getString("updated_time"));
                } catch (JSONException e) {
                }
            }
        } catch (JSONException e) {
            // TODO: Log here something, at least during development.
        }
    }
}

From source file:com.fortydegree.ra.data.JsonUnmarshaller.java

public static List<Marker> load(JSONObject root) throws JSONException {
    JSONObject jo = null;/*from  w  ww .  j  av a2 s  .c  o  m*/
    JSONArray dataArray = null;
    List<Marker> markers = new ArrayList<Marker>();

    if (root.has("results")) {
        dataArray = root.getJSONArray("results");

        int top = Math.min(MAX_JSON_OBJECTS, dataArray.length());

        for (int i = 0; i < top; i++) {
            jo = dataArray.getJSONObject(i);
            Marker ma = processGeoserviceJSONObject(jo);
            if (ma != null)
                markers.add(ma);
        }
    }

    return markers;
}

From source file:ch.lom.clemens.android.bibliography.data.JSONWebConnector.java

public MCollection[] getCollections() {

    if (!isConnected()) {
        StartActivity.singleton.doAuthentication(StartActivity.MENDELEY_RETRIEVE_COLLECTIONS);
        return null;
    }// w  ww.j a va  2  s . c  o  m

    MCollection[] collections = null;

    try {
        String strResponse = connect(
                "http://www.mendeley.com/oapi/library/collections?consumer_key=" + m_consumerkey);

        Log.i("MendeleyComm", strResponse);

        JSONArray jcols = new JSONArray(strResponse);

        collections = new MCollection[jcols.length()];

        for (int i = 0; i < jcols.length(); i++) {
            JSONObject collection = jcols.getJSONObject(i);

            collections[i] = new MCollection(null);

            collections[i].id = collection.getString("id");
            collections[i].name = collection.getString("name");
            collections[i].type = collection.getString("type");
            collections[i].size = collection.getInt("size");
        }
    } catch (Exception e) {
        Log.e("MendeleyConnector", "Got exception when parsing online collection data");
        Log.e("MendeleyConnector", e.getClass().getSimpleName() + ": " + e.getMessage());
    }
    return collections;

}

From source file:ch.lom.clemens.android.bibliography.data.JSONWebConnector.java

public MGroup[] getGroups(MendeleyConnector con) {

    if (!isConnected()) {
        StartActivity.singleton.doAuthentication(StartActivity.MENDELEY_RETRIEVE_COLLECTIONS);
        return null;
    }/*from   w  w  w.  j ava2s . c  om*/

    MGroup[] groups = null;

    try {
        String strResponse = connect(
                "http://www.mendeley.com/oapi/library/groups?consumer_key=" + m_consumerkey);

        Log.i("MendeleyComm", strResponse);

        JSONArray items = new JSONArray(strResponse);

        groups = new MGroup[items.length()];

        for (int i = 0; i < items.length(); i++) {
            JSONObject collection = items.getJSONObject(i);

            groups[i] = new MGroup(con);

            groups[i].id = collection.getString("id");
            groups[i].name = collection.getString("name");
            groups[i].type = collection.getString("type");
            groups[i].size = collection.getInt("size");
        }
    } catch (Exception e) {
        Log.e("MendeleyConnector", "Got exception when parsing online group data");
        Log.e("MendeleyConnector", e.getClass().getSimpleName() + ": " + e.getMessage());
    }
    return groups;
}

From source file:gmc.hotplate.util.JsonParser.java

public List<Recipe> parseMessage(JSONObject obj) {
    List<Recipe> recipes = new ArrayList<Recipe>();
    try {//from   www  . j  a  v  a 2 s . c  om
        JSONArray jsonRecipes = obj.getJSONArray(TAG_RECIPES);
        for (int i = 0; i < jsonRecipes.length(); i++) {
            Recipe recipe = parseRecipeObject(jsonRecipes.getJSONObject(i));
            if (recipe != null) {
                recipes.add(recipe);
            }
        }
    } catch (JSONException e) {
        Log.w(LOG_TAG, "ParseMessage() error: " + e.getMessage());
    }
    return recipes;
}

From source file:gmc.hotplate.util.JsonParser.java

public Recipe parseRecipeObject(JSONObject obj) {
    Recipe recipe = null;/*  w  ww.  ja  v a 2  s .c  om*/
    try {
        int recipeId = obj.getInt(TAG_RECIPE_ID);
        String recipeName = obj.getString(TAG_RECIPE_NAME);
        String recipeDescription = obj.getString(TAG_RECIPE_DESCRIPTION);
        int personCount = obj.getInt(TAG_RECIPE_PERSON);
        JSONArray jsonSteps = obj.getJSONArray(TAG_RECIPE_STEPS);
        List<Step> steps = new ArrayList<Step>();
        for (int i = 0; i < jsonSteps.length(); i++) {
            Step step = parseStepObject(jsonSteps.getJSONObject(i));
            if (step != null) {
                steps.add(step);
            }
        }

        List<Ingredient> ingredients = new ArrayList<Ingredient>();
        JSONArray jsonIngredients = obj.getJSONArray(TAG_RECIPE_INGREDIENTS);
        for (int i = 0; i < jsonIngredients.length(); i++) {
            Ingredient ingredient = parseIngredientObject(jsonIngredients.getJSONObject(i));
            if (ingredient != null) {
                ingredients.add(ingredient);
            }
        }

        List<String> categories = new ArrayList<String>();
        if (obj.has(TAG_RECIPE_CATEGORIES)) {
            JSONArray jsonCategories = obj.getJSONArray(TAG_RECIPE_CATEGORIES);
            for (int i = 0; i < jsonCategories.length(); i++) {
                String tag = jsonCategories.getString(i);
                categories.add(tag);
            }
        }
        recipe = new Recipe(recipeId, recipeName, recipeDescription, personCount, steps);
        recipe.setIngredients(ingredients);
        recipe.setCategories(categories);
    } catch (JSONException e) {
        Log.w(LOG_TAG, "ParseRecipe() error: " + e.getMessage());
    }

    return recipe;
}

From source file:org.wso2.carbon.connector.integration.test.gototraining.GototrainingConnectorIntegrationTest.java

/**
 * Positive test case for listTrainings method with mandatory parameters.
 *///from  w ww  .ja v a 2s  . c o  m
@Test(groups = { "wso2.esb" }, dependsOnMethods = { "testCreateTrainingWithMandatoryParameters",
        "testCreateTrainingWithOptionalParameters" }, description = "gototraining {listTrainings} integration test with mandatory parameters.")
public void testListTrainingsWithMandatoryParameters() throws IOException, JSONException {

    esbRequestHeadersMap.put("Action", "urn:listTrainings");

    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_listTrainings_mandatory.json");

    final String apiEndPoint = apiRequestUrl + "/organizers/" + connectorProperties.getProperty("organizerKey")
            + "/trainings/";

    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap);

    final JSONArray esbArray = new JSONArray(esbRestResponse.getBody().getString("output"));
    final JSONArray apiArray = new JSONArray(apiRestResponse.getBody().getString("output"));

    Assert.assertEquals(esbArray.length(), apiArray.length());
    Assert.assertEquals(esbArray.getJSONObject(0).getString("name"),
            apiArray.getJSONObject(0).getString("name"));
    Assert.assertEquals(esbArray.getJSONObject(0).getString("description"),
            apiArray.getJSONObject(0).getString("description"));
    Assert.assertEquals(esbArray.getJSONObject(0).getJSONArray("times").getJSONObject(0).getString("startDate"),
            apiArray.getJSONObject(0).getJSONArray("times").getJSONObject(0).getString("startDate"));
}

From source file:org.wso2.carbon.connector.integration.test.gototraining.GototrainingConnectorIntegrationTest.java

/**
 * Positive test case for listOrganizers method with mandatory parameters.
 *//* w  w  w  .  ja v  a2  s.  c  o m*/
@Test(dependsOnMethods = { "testCreateTrainingWithMandatoryParameters" }, groups = {
        "wso2.esb" }, description = "gototraining {listOrganizers} integration test with mandatory parameters.")
public void testListOrganizersWithMandatoryParameters() throws IOException, JSONException {

    esbRequestHeadersMap.put("Action", "urn:listOrganizers");

    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_listOrganizers_mandatory.json");

    final String apiEndPoint = apiRequestUrl + "/organizers/" + connectorProperties.getProperty("organizerKey")
            + "/trainings/" + connectorProperties.getProperty("trainingKeyMandatory") + "/organizers";

    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap);

    final JSONArray esbArray = new JSONArray(esbRestResponse.getBody().getString("output"));
    final JSONArray apiArray = new JSONArray(apiRestResponse.getBody().getString("output"));

    Assert.assertEquals(esbArray.length(), apiArray.length());
    Assert.assertEquals(esbArray.getJSONObject(0).getString("givenName"),
            apiArray.getJSONObject(0).getString("givenName"));
    Assert.assertEquals(esbArray.getJSONObject(0).getString("email"),
            apiArray.getJSONObject(0).getString("email"));
    Assert.assertEquals(esbArray.getJSONObject(0).getString("surname"),
            apiArray.getJSONObject(0).getString("surname"));
}

From source file:org.wso2.carbon.connector.integration.test.gototraining.GototrainingConnectorIntegrationTest.java

/**
 * Positive test case for listRegistrants method with mandatory parameters.
 *///  ww  w.ja v a2 s. c  om
@Test(groups = { "wso2.esb" }, dependsOnMethods = {
        "testAddRegistrantWithMandatoryParameters" }, description = "gototraining {listRegistrants} integration test with mandatory parameters.")
public void testListRegistrantsWithMandatoryParameters() throws IOException, JSONException {

    esbRequestHeadersMap.put("Action", "urn:listRegistrants");

    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_listRegistrants_mandatory.json");

    final String apiEndPoint = apiRequestUrl + "/organizers/" + connectorProperties.getProperty("organizerKey")
            + "/trainings/" + connectorProperties.getProperty("trainingKeyMandatory") + "/registrants";

    final RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET",
            apiRequestHeadersMap);

    final JSONArray esbArray = new JSONArray(esbRestResponse.getBody().getString("output"));
    final JSONArray apiArray = new JSONArray(apiRestResponse.getBody().getString("output"));

    Assert.assertEquals(esbArray.length(), apiArray.length());
    Assert.assertEquals(esbArray.getJSONObject(0).getString("givenName"),
            apiArray.getJSONObject(0).getString("givenName"));
    Assert.assertEquals(esbArray.getJSONObject(0).getString("email"),
            apiArray.getJSONObject(0).getString("email"));
    Assert.assertEquals(esbArray.getJSONObject(0).getString("status"),
            apiArray.getJSONObject(0).getString("status"));
}