Example usage for org.json JSONObject getJSONArray

List of usage examples for org.json JSONObject getJSONArray

Introduction

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

Prototype

public JSONArray getJSONArray(String key) throws JSONException 

Source Link

Document

Get the JSONArray value associated with a key.

Usage

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

public static RadioEpisode GetCurrentEpisodeInformation(Context context, RadioRedditApplication application) {
    RadioEpisode radioepisode = new RadioEpisode();
    radioepisode.ErrorMessage = "";

    try {/*w w  w .  j  a v  a2  s.  co  m*/
        String status_url = context.getString(R.string.radio_reddit_base_url) + application.CurrentStream.Status
                + context.getString(R.string.radio_reddit_status);

        String outputStatus = "";
        boolean errorGettingStatus = false;

        try {
            outputStatus = HTTPUtil.get(context, status_url);
        } catch (Exception ex) {
            ex.printStackTrace();
            errorGettingStatus = true;
            // For now, not used. It is acceptable to error out and not alert the user
            // radiosong.ErrorMessage = context.getString(R.string.error_RadioRedditServerIsDownNotification);
        }

        if (!errorGettingStatus && outputStatus.length() > 0) {
            JSONTokener status_tokener = new JSONTokener(outputStatus);
            JSONObject status_json = new JSONObject(status_tokener);

            radioepisode.Playlist = status_json.getString("playlist");

            JSONObject episodes = status_json.getJSONObject("episodes");
            JSONArray episodes_array = episodes.getJSONArray("episode");

            // get the first episode in the array
            JSONObject song = episodes_array.getJSONObject(0);
            radioepisode.ID = song.getInt("id");
            radioepisode.EpisodeTitle = song.getString("episode_title");
            radioepisode.EpisodeDescription = song.getString("episode_description");
            radioepisode.EpisodeKeywords = song.getString("episode_keywords");
            radioepisode.ShowTitle = song.getString("show_title");
            radioepisode.ShowHosts = song.getString("show_hosts").replaceAll(",", ", ");
            radioepisode.ShowRedditors = song.getString("show_redditors").replaceAll(",", ", ");
            radioepisode.ShowGenre = song.getString("show_genre");
            radioepisode.ShowFeed = song.getString("show_feed");
            radioepisode.Reddit_title = song.getString("reddit_title");
            radioepisode.Reddit_url = song.getString("reddit_url");
            if (song.has("preview_url"))
                radioepisode.Preview_url = song.getString("preview_url");
            if (song.has("download_url"))
                radioepisode.Download_url = song.getString("download_url");

            // 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");

                // Episode 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 = "";
            }

            return radioepisode;
        }
        return null;
    } catch (Exception ex) {
        // We fail to get the current song information...
        CustomExceptionHandler ceh = new CustomExceptionHandler(context);
        ceh.sendEmail(ex);

        ex.printStackTrace();
        radioepisode.ErrorMessage = ex.toString();
        return radioepisode;
    }

}

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

public static List<RadioSong> GetTopChartsByType(Context context, RadioRedditApplication application,
        String type) {// ww  w .ja v a  2  s  . c  o  m
    List<RadioSong> radiosongs = new ArrayList<RadioSong>();

    try {
        String chart_url = "";

        if (type.equals("all"))
            chart_url = context.getString(R.string.radio_reddit_charts_all);
        else if (type.equals("month"))
            chart_url = context.getString(R.string.radio_reddit_charts_month);
        else if (type.equals("week"))
            chart_url = context.getString(R.string.radio_reddit_charts_week);
        else if (type.equals("day"))
            chart_url = context.getString(R.string.radio_reddit_charts_day);

        // TODO: might could merge this code with GetCurrentSongInformation

        String outputStatus = "";
        boolean errorGettingStatus = false;

        try {
            outputStatus = HTTPUtil.get(context, chart_url);
        } catch (Exception ex) {
            ex.printStackTrace();
            errorGettingStatus = true;
            // For now, not used. It is acceptable to error out and not alert the user
            // radiosong.ErrorMessage = context.getString(R.string.error_RadioRedditServerIsDownNotification);
        }

        if (!errorGettingStatus && outputStatus.length() > 0) {
            JSONTokener status_tokener = new JSONTokener(outputStatus);
            JSONObject status_json = new JSONObject(status_tokener);

            JSONObject songs = status_json.getJSONObject("songs");
            JSONArray songs_array = songs.getJSONArray("song");

            // get the first song in the array
            for (int i = 0; i < songs_array.length(); i++) {
                RadioSong radiosong = new RadioSong();
                radiosong.ErrorMessage = "";

                JSONObject song = songs_array.getJSONObject(i);
                //radiosong.ID = song.getInt("id");
                radiosong.Title = song.getString("title");
                radiosong.Artist = song.getString("artist");
                radiosong.Redditor = song.getString("redditor");
                radiosong.Genre = song.getString("genre");
                //radiosong.CumulativeScore = song.getString("score");

                //if(radiosong.CumulativeScore.equals("{}"))
                //   radiosong.CumulativeScore = null;   

                radiosong.Reddit_title = song.getString("reddit_title");
                radiosong.Reddit_url = song.getString("reddit_url");
                if (song.has("preview_url"))
                    radiosong.Preview_url = song.getString("preview_url");
                if (song.has("download_url"))
                    radiosong.Download_url = song.getString("download_url");
                if (song.has("bandcamp_link"))
                    radiosong.Bandcamp_link = song.getString("bandcamp_link");
                if (song.has("bandcamp_art"))
                    radiosong.Bandcamp_art = song.getString("bandcamp_art");
                if (song.has("itunes_link"))
                    radiosong.Itunes_link = song.getString("itunes_link");
                if (song.has("itunes_art"))
                    radiosong.Itunes_art = song.getString("itunes_art");
                if (song.has("itunes_price"))
                    radiosong.Itunes_price = song.getString("itunes_price");

                radiosongs.add(radiosong);
            }
        }
    } catch (Exception ex) {
        // We fail to get the current song information...
        CustomExceptionHandler ceh = new CustomExceptionHandler(context);
        ceh.sendEmail(ex);

        ex.printStackTrace();
        // TODO: return error message?? Might need to wrap List<RadioSong> in an object that has an ErrorMessage data member
        //radiosong.ErrorMessage = ex.toString();
        //return radiosong;
    }
    return radiosongs;
}

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

public static RadioSong GetSongVoteScore(Context context, RadioRedditApplication application,
        RadioSong radiosong) {/*from  www . j a va  2s. c o m*/
    try {
        // get vote score 
        String reddit_info_url = context.getString(R.string.reddit_link_by)
                + URLEncoder.encode(radiosong.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");
            }

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

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

    return radiosong;
}

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

public static RadioEpisode GetEpisodeVoteScore(Context context, RadioRedditApplication application,
        RadioEpisode radioepisode) {/*from   w  ww  .  ja v a 2  s . com*/
    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:com.fortydegree.ra.data.JsonUnmarshaller.java

public static List<Marker> load(JSONObject root) throws JSONException {
    JSONObject jo = null;//from   ww w  . j  ava2  s  . c  om
    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 String[] getCollectionDocIDs(MCollection col, int page) {
    if (!isConnected()) {
        StartActivity.singleton.doAuthentication(StartActivity.MENDELEY_RETRIEVE_COLLECTION);
        return null;
    }/*from   w w w  .ja  v  a  2s  .c  o m*/

    String[] ids = null;
    try {
        String strResponse;
        if (col.m_coltype == MCollection.AUTHORED) {
            strResponse = connect("http://www.mendeley.com/oapi/library/documents/authored/?page=" + page
                    + "&consumer_key=" + m_consumerkey);
        } else if (col.m_coltype == MCollection.LIBRARY) {
            strResponse = connect(
                    "http://www.mendeley.com/oapi/library/?page=" + page + "&consumer_key=" + m_consumerkey);
        } else {
            strResponse = connect("http://www.mendeley.com/oapi/library/collections/" + col.id + "/?page="
                    + page + "&consumer_key=" + m_consumerkey);
        }

        Log.i("MendeleyComm", "Collection: " + col.id + "\n" + strResponse);

        JSONObject colData = new JSONObject(strResponse);

        JSONArray documents = colData.getJSONArray("document_ids");
        ids = new String[documents.length()];
        for (int i = 0; i < documents.length(); i++) {
            ids[i] = documents.getString(i);
        }

        // make sure we get all pages
        int totalpages = colData.getInt("total_pages");
        if (page + 1 < totalpages) {
            String[] adddocs = getCollectionDocIDs(col, page + 1);

            String[] alldocs = new String[ids.length + adddocs.length];
            for (int i = 0; i < ids.length; i++)
                alldocs[i] = ids[i];
            for (int i = 0; i < adddocs.length; i++)
                alldocs[ids.length + i] = adddocs[i];
            ids = alldocs;
        }

    } catch (Exception e) {
        Log.e("MendeleyConnector", "Got a " + e.getClass().getName() + ": " + e.getMessage());
    }

    return ids;
}

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

public String[] getGroupDocuments(MGroup group, int page) {
    if (!isConnected()) {
        StartActivity.singleton.doAuthentication(StartActivity.MENDELEY_RETRIEVE_COLLECTION);
        return null;
    }/*from  w ww.j a  va  2  s . co m*/

    String[] ids = null;
    try {
        String strResponse = connect("http://www.mendeley.com/oapi/library/groups/" + group.id + "/?page="
                + page + "&consumer_key=" + m_consumerkey);

        Log.i("MendeleyComm", "Collection: " + group.id + "\n" + strResponse);

        JSONObject colData = new JSONObject(strResponse);

        JSONArray documents = colData.getJSONArray("document_ids");
        ids = new String[documents.length()];
        for (int i = 0; i < documents.length(); i++) {
            ids[i] = documents.getString(i);
        }

        // make sure we get all pages
        int totalpages = colData.getInt("total_pages");
        if (page + 1 < totalpages) {
            String[] adddocs = getGroupDocuments(group, page + 1);

            String[] alldocs = new String[ids.length + adddocs.length];
            for (int i = 0; i < ids.length; i++)
                alldocs[i] = ids[i];
            for (int i = 0; i < adddocs.length; i++)
                alldocs[ids.length + i] = adddocs[i];
            ids = alldocs;
        }

    } catch (Exception e) {
        Log.e("MendeleyConnector", "Got a " + e.getClass().getName() + ": " + e.getMessage());
    }

    return ids;
}

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

private MDocument parseDocumentResult(MDocument mdoc, String strResponse) throws JSONException {

    JSONObject doc = new JSONObject(strResponse);

    try {/*from w  w w  .jav  a2 s.  co m*/
        mdoc.title = doc.getString("title");
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document title");
    }
    try {
        mdoc.year = doc.getString("year");
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document year");
    }
    try {
        mdoc.notes = doc.getString("notes");
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document notes");
    }
    try {
        mdoc.type = doc.getString("type");
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document type");
    }
    try {
        mdoc.urls = new String[] { doc.getString("url") };
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document url");
    }
    try {
        mdoc.pages = doc.getString("pages");
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document pages");
    }
    try {
        mdoc.docabstract = doc.getString("abstract");
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document abstract");
    }

    try {
        JSONArray authors = doc.getJSONArray("authors");
        String[] strAuthors = new String[authors.length()];
        for (int j = 0; j < authors.length(); j++) {
            strAuthors[j] = authors.getString(j);
        }
        mdoc.authors = strAuthors;
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document authors");
    }

    try {

        JSONArray tags = doc.getJSONArray("tags");
        String[] mtags = new String[tags.length()];
        for (int j = 0; j < tags.length(); j++) {
            mtags[j] = tags.getString(j);
        }
        mdoc.tags = mtags;
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document tags");
    }

    try {
        JSONObject ids = doc.getJSONObject("identifiers");
        mdoc.identifiers = new HashMap<String, String>();
        JSONArray names = ids.names();
        for (int j = 0; j < names.length(); j++) {
            mdoc.identifiers.put(names.getString(j), ids.getString(names.getString(j)));
        }
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document identifiers");
    }

    try {
        JSONObject ids = doc.getJSONObject("discipline");
        mdoc.discipline = new HashMap<String, String>();
        JSONArray names = ids.names();
        for (int j = 0; j < names.length(); j++) {
            mdoc.discipline.put(names.getString(j), ids.getString(names.getString(j)));
        }
    } catch (JSONException e) {
        Log.w("WebConnector", "Parsing error while getting document disciplines");
    }

    return mdoc;
}

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

public List<Recipe> parseMessage(JSONObject obj) {
    List<Recipe> recipes = new ArrayList<Recipe>();
    try {//from www.  ja v  a2s.c o  m
        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;// ww  w.  j  a  va2 s  .  co m
    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;
}