Shawn
Shawn

Reputation: 1382

JSON parsing assitance

I can log the JSON file in my app but I'm having troubles parsing the JSON file. I'm trying to get the name of each recipe so I can display it in a RecyclerView. I do need more data from the JSON later on, would it be better to do all the parsing at once or as needed?

Here is the link to the JSON https://d17h27t6h515a5.cloudfront.net/topher/2017/May/59121517_baking/baking.json

JSONObject recipeObject = new JSONObject(jsonString);
JSONArray recipeResults = recipeObject.getJSONArray("name");

Log.d(LOGTAG, "Recipe Results " + recipeResults.toString());

This is the log result

2018-12-13 13:56:43.622 31472-31472/com.shawn.nichol.bakingapp W/System.err:     at com.bakingapp.Data.ExtractRecipeData.recipeData(ExtractRecipeData.java:19)

Upvotes: 1

Views: 67

Answers (2)

corn3lius
corn3lius

Reputation: 4985

The base object is an array of objects.

Try this:

JSONArray recipes = new JSONArray(jsonString); 

for(int i = 0; i < recipes.length(); i++){ 
    JSONObject recipe = recipes.getJSONObject(i); 
    Log.d(LOGTAG, "Recipe name: " + recipe.getString("name"));
}

Upvotes: 3

Master Fathi
Master Fathi

Reputation: 349

first of all you need to use a tool to better understand your json structure I use jsoneditoronline see in the link the preview of your jsonobject http://jsoneditoronline.org/?id=dac21affd6544a00a553360e2c9fa311

The parsing is better done at first then you pass your data to the RecyclerViewAdapter this library should help you a lot https://github.com/google/gson here is a tutorial for gson : https://howtodoinjava.com/apache-commons/google-gson-tutorial-convert-java-object-to-from-json/

Before trying to access name you need to access an item of the array let's say you need to get the name of the first object that is the nutella pie you do like this

JSONArray myJsonArray = new JSONArray(jsonString);
JSONObject recipeObject = myJsonArray.getJSONObject(0);

Log.d(LOGTAG, "Recipe Name" + recipeObject.getString("name").toString());

if you want to convert your JSON into java you need to

Recipe recipe= gson.fromJson(recipeObject.toString(), Recipe.class);

get all the data as so

List<Recipe> recipeList = new ArrayList();
Gson gson = new Gson();
for (int i = 0; i < jsonArray.length(); i++) {
   Recipe recipe= gson.fromJson(myJsonArray .get(i).toString(), Recipe.class);
   recipeList.add(recipe);
}

Upvotes: 3

Related Questions