JSON Parsing (org.json/Gson)

No matter which HTTP client you use, at some point a JSON string coming from the server needs to become Java objects your app can work with. This lesson compares two approaches: parsing manually with Android's built-in org.json classes, and letting Gson do the conversion automatically.

Manual Parsing with org.json

org.json ships with Android – no Gradle dependency needed. It gives you JSONObject and JSONArray, which you read field by field:

// Manually parsing one recipe object
JSONObject jsonObject = new JSONObject(jsonString);

String id = jsonObject.getString("id");
String title = jsonObject.getString("title");
int prepMinutes = jsonObject.getInt("prep_minutes");

List<String> ingredients = new ArrayList<>();
JSONArray ingredientsArray = jsonObject.getJSONArray("ingredients");
for (int i = 0; i < ingredientsArray.length(); i++) {
    ingredients.add(ingredientsArray.getString(i));
}

Recipe recipe = new Recipe(id, title, ingredients, prepMinutes);

Parsing a whole array of recipes means looping over a JSONArray of objects:

// Manually parsing a list of recipes
List<Recipe> recipes = new ArrayList<>();
JSONArray recipesArray = new JSONArray(jsonString);

for (int i = 0; i < recipesArray.length(); i++) {
    JSONObject item = recipesArray.getJSONObject(i);
    recipes.add(new Recipe(
            item.getString("id"),
            item.getString("title"),
            /* ... remaining fields ... */
            item.getInt("prep_minutes")
    ));
}
Honest downside: this works, but it is genuinely tedious and error-prone once a class has more than a handful of fields, or contains nested objects and arrays. Every field name is a string typed by hand, every missing key throws a JSONException you must catch, and adding a new field to Recipe means updating parsing code in multiple places.

Automatic Parsing with Gson

Gson, already used by the Gson converter in android-retrofit-java.php, maps JSON fields to a Java class's fields by name automatically – no manual field-by-field code required:

String jsonString = "{\"id\":\"r1\",\"title\":\"Masala Omelette\",\"prep_minutes\":10}";

Gson gson = new Gson();
Recipe recipe = gson.fromJson(jsonString, Recipe.class);

And for a whole list, Gson needs a small helper type to describe the generic list shape:

Type recipeListType = new TypeToken<List<Recipe>>(){}.getType();
List<Recipe> recipes = gson.fromJson(jsonArrayString, recipeListType);
Explanation: Gson reads the class's fields via reflection and matches them to JSON keys of the same name. One line replaces the entire manual loop from the previous section.

@SerializedName for Mismatched Names

Just like in the Retrofit lesson, when a JSON key doesn't match the Java field name exactly – for example "prep_minutes" versus prepMinutes – annotate the field:

public class Recipe {
    private String id;
    private String title;

    @SerializedName("prep_minutes")
    private int prepMinutes;

    // ...
}

Converting a Java Object Back to JSON

Gson also works in reverse – turning a Java object into a JSON string, useful when submitting data with OkHttp or Retrofit:

Recipe newRecipe = new Recipe("r99", "Paneer Tikka", ingredients, steps,
        "content://photos/r99", "dinner", 35);

String json = new Gson().toJson(newRecipe);
// {"id":"r99","title":"Paneer Tikka", ... ,"prep_minutes":35}
Explanation: toJson() walks the object's fields the same way fromJson() reads them, respecting any @SerializedName annotations in both directions.

A Note on Moshi

Moshi, from Square (the same team behind OkHttp and Retrofit), is another popular JSON library seen in some Java Android projects. It is fast and has strong Kotlin support, though its Java ergonomics historically required a bit more setup (adapters, code generation) than Gson's simpler reflection-based approach – which is part of why Gson has remained the more common default for Java-first projects.

Which Should You Use?

ApproachBest for
org.jsonGenuinely tiny, one-off parsing needs where pulling in a full library feels like overkill
GsonMost real projects – simple API, no extra ceremony, works directly with Retrofit
MoshiProjects that want Square's tooling and are open to its setup, especially mixed Java/Kotlin codebases
Recommendation: reach for Gson (or a Retrofit converter built on it) for RecipeBox-style apps. Keep org.json in your back pocket for quick, throwaway parsing where adding a dependency isn't worth it.
Next up: WebSockets (OkHttp) – for when a one-off HTTP request isn't enough and you need a live, two-way connection to the server.