Parsing JSON data in Android

APIs return data as JSON text, so your app must parse it: Android's JSONObject and JSONArray let you read fields out of that text into usable Kotlin values you can show on screen.

11 min read · 8 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

The data arrives as text

When your app calls an events API, the response is JSON text, a string like [{"name":"Robotics","seats":50}]. Your app cannot show a raw string usefully; it must parse the JSON, pull the values out, so it can display 'Robotics, 50 seats'.

Parsing JSON is a core skill for consuming any API. You met JSON's shape earlier; this lesson shows how to read it in Android using JSONObject and JSONArray. Once you can turn a JSON response into Kotlin values, you can use data from any web service.

Practical

A JSON response from an events API

{
  "events": [
    { "name": "Robotics Workshop", "seats": 50 },
    { "name": "Coding Contest",   "seats": 30 }
  ]
}
// An object { } with a key 'events' whose value is an array [ ] of objects.
// Your app must read 'name' and 'seats' out of each item.

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Theory

Parsing with JSONObject and JSONArray

Android's built-in org.json classes parse JSON text.

JSONObject(text) parses a JSON object; you read fields with typed getters: getString("name"), getInt("seats"). JSONArray represents a JSON list; length() gives its size and getJSONObject(i) gets the item at index i.

So to read the events response: make a JSONObject from the text, get the events JSONArray, then loop it, pulling name and seats from each item into your Kotlin objects. That is the whole pattern, parse the container, then loop and extract, and it works for any JSON shape once you know the structure.

Practical

Parsing the events JSON in Android

val root = JSONObject(responseText)          // parse the object
val eventsArray = root.getJSONArray("events") // the JSON array

val events = mutableListOf<Pair<String, Int>>()
for (i in 0 until eventsArray.length()) {     // loop the items
    val item = eventsArray.getJSONObject(i)
    val name = item.getString("name")
    val seats = item.getInt("seats")
    events.add(name to seats)
}
// events now holds [("Robotics Workshop", 50), ("Coding Contest", 30)]

Formula

Match the getter to the structure

Parsing correctly means matching your code to the JSON's structure and types. Use getJSONObject/getJSONArray to descend into nested objects and arrays, and the typed getters (getString, getInt, getBoolean) for the leaf values, matching each key's actual type.

Get the shape wrong, treating an array as an object, or reading a number as a string, and parsing fails. So always know the JSON's structure first (from the API's documentation or a sample response). For larger apps, libraries like Gson or Moshi can map JSON straight into Kotlin data classes automatically, saving manual parsing, but understanding the manual way first makes those libraries make sense.

Quiz

The API returns { "events": [ ... ] }. In Android, how do you get the list of events to loop over?

  1. root.getString("events"), because everything is a string
  2. root.getJSONArray("events"), then loop from 0 until its length(), using getJSONObject(i) for each item
  3. root.getInt("events"), because the list has a size
  4. You cannot read arrays in Android
Show the answer

root.getJSONArray("events"), then loop from 0 until its length(), using getJSONObject(i) for each item

The value of 'events' is a JSON array, so you read it with root.getJSONArray('events'), then loop from 0 until array.length() and use getJSONObject(i) to get each event object (from which you read name and seats). Option A is wrong: 'events' is an array, not a string, so getString would fail or misread it, you must match the getter to the actual type. Option C is wrong: the array is a list of objects, not an integer; getInt does not apply. Option D is false: Android's JSONArray reads arrays fine. The rule: match the getter (getJSONArray for a list, getJSONObject for an object, getString/getInt for leaves) to the JSON's structure.

Think first

Why is JSON the standard format for API data?

APIs almost always return JSON. Why did JSON become the default over other formats? Then tap.

Show the answer

Because JSON is LIGHTWEIGHT, HUMAN-READABLE, and UNIVERSALLY SUPPORTED, hitting a sweet spot that older formats missed. It is lightweight: JSON's syntax is minimal (braces, brackets, colons, commas), so responses are compact and quick to send over a network, which matters on mobile connections. It is human-readable: you can look at a JSON response and understand it at a glance, which makes developing and debugging APIs far easier than opaque binary formats. It maps naturally to the data structures every language already has: JSON objects are just key-value maps and arrays are just lists, so virtually every programming language, Kotlin, JavaScript, Python, Java, has built-in or easy support to produce and parse it (as you just did with org.json). That universality means an API can return JSON and be consumed by clients written in anything, which is exactly what web services need for interoperability. Historically, XML filled this role but is far more verbose and cumbersome to parse, so as web and mobile apps exploded, the industry gravitated to JSON's simpler, lighter model (which, being derived from JavaScript object syntax, was also a perfect fit for the web). The combination, small on the wire, easy for humans, trivial for machines, and supported everywhere, is why JSON became the de facto language of APIs. Simple, readable, and universal beats heavy and complex.

Summary

Key takeaways

  • APIs return data as JSON text, which your app must parse to use.
  • JSON is objects { } of key-value pairs, arrays [ ], and values (strings, numbers, booleans, null).
  • Android's org.json parses it: JSONObject(text) for an object, JSONArray for a list.
  • Read fields with typed getters: getString, getInt, getBoolean; descend with getJSONObject and getJSONArray.
  • Pattern: parse the container, get the array, loop from 0 until length(), extract each item's fields.
  • Match getters to the JSON's actual structure and types; libraries like Gson/Moshi can map JSON to data classes automatically.
  • Memory hook: JSONObject and JSONArray, loop the array, pull fields with typed getters.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Working with Data and API in Android

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Parsing JSON data in Android · Advance Mobile Application Development - II (Major-15-02) · Gri-Learn