Parsing JSON data in Android

APIs data JSON text તરીકે આપે છે, એટલે appએ તેને parse કરવું પડે છે. Androidના JSONObject અને JSONArrayથી textમાંથી fields વાંચીને usable Kotlin valuesમાં ફેરવી શકાય છે.

11 min read · 8 cards · 2 checks

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


Theory

Data text તરીકે આવે છે

તમારું app events APIને call કરે ત્યારે response JSON text હોય છે, જેમ કે [{"name":"Robotics","seats":50}]. App raw stringને ઉપયોગી રીતે બતાવી શકતું નથી; તેને parse કરવું પડે છે, એટલે textમાંથી values કાઢવી પડે છે, જેથી screen પર 'Robotics, 50 seats' બતાવી શકાય.

કોઈ પણ API consume કરવા JSON parsing core skill છે. અગાઉ તમે JSONનું shape જોયું હતું; આ lesson Androidમાં JSONObject અને JSONArray વડે તેને read કરવાની રીત બતાવે છે. JSON responseને Kotlin valuesમાં ફેરવતા આવડે એટલે કોઈ પણ web serviceનો data વાપરી શકો છો.

Practical

Events APIમાંથી JSON response

{
  "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

JSONObject અને JSONArrayથી parsing

Androidની built-in org.json classes JSON text parse કરે છે.

JSONObject(text) JSON object parse કરે છે. Fields typed getters વડે વાંચો: getString("name"), getInt("seats"). JSONArray JSON list represent કરે છે; length() listનું size આપે છે અને getJSONObject(i) index i પરનું item આપે છે.

Events response વાંચવાનો pattern છે: textમાંથી JSONObject બનાવો, તેમાંનું events JSONArray મેળવો, પછી તેને loop કરીને દરેક itemમાંથી name અને seats કાઢો અને Kotlin objectsમાં મૂકો. પહેલાં container parse કરો, પછી loop કરીને fields extract કરો; JSON structure જાણીતું હોય ત્યારે આ pattern કોઈ પણ response માટે કામ કરે છે.

Practical

Androidમાં events JSON parse કરવું

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

Getterને JSON structure સાથે match કરો

સાચી parsing માટે codeને JSONના structure અને types સાથે match કરવો જરૂરી છે. Nested objects અને arraysમાં નીચે જવા getJSONObject અને getJSONArray વાપરો. Leaf values માટે typed getters, જેમ કે getString, getInt અને getBoolean, વાપરો અને તે keyના actual type સાથે match થવા જોઈએ.

Arrayને object માનશો અથવા numberને string તરીકે વાંચશો તો parsing fail થઈ શકે છે. તેથી પહેલાં API documentation અથવા sample responseથી JSON structure સમજો. મોટા appsમાં Gson અથવા Moshi JSONને સીધું Kotlin data classesમાં map કરી શકે છે અને manual parsing બચાવે છે. પરંતુ manual method સમજવાથી આ libraries કેવી રીતે કામ કરે છે તે વધુ સારી રીતે સમજાય છે.

Quiz

API `{ "events": [ ... ] }` return કરે છે. Androidમાં loop કરવા eventsની list કેવી રીતે મેળવો?

  1. `root.getString("events")`, કારણ કે બધું string છે
  2. `root.getJSONArray("events")`, પછી `length()` સુધી loop કરો અને દરેક item માટે `getJSONObject(i)` વાપરો
  3. `root.getInt("events")`, કારણ કે listનું size છે
  4. Androidમાં arrays read કરી શકાતા નથી
Show the answer

`root.getJSONArray("events")`, પછી `length()` સુધી loop કરો અને દરેક item માટે `getJSONObject(i)` વાપરો

eventsની value JSON array છે, તેથી તેને root.getJSONArray('events')થી વાંચો. પછી 0 until array.length() સુધી loop કરીને દરેક event object માટે getJSONObject(i) વાપરો અને તેમાંનાથી name તથા seats વાંચો. Option A ખોટું છે: events array છે, string નહીં; getter actual type સાથે match થવો જોઈએ. Option C ખોટું છે: array objectsની list છે, integer નહીં. Option D ખોટું છે: Androidનું JSONArray arraysને સારી રીતે read કરે છે. Rule: list માટે getJSONArray, object માટે getJSONObject અને leaf values માટે getString/getInt જેવા matching getters વાપરો.

Think first

API data માટે JSON standard format કેમ બન્યું?

APIs સામાન્ય રીતે JSON return કરે છે. બીજા formats કરતાં JSON default કેમ બન્યું? પછી tap.

Show the answer

કારણ કે JSON LIGHTWEIGHT, HUMAN-READABLE અને UNIVERSALLY SUPPORTED છે. તે ત્રણેય બાબતોનું સારું balance આપે છે.

JSON syntax simple છે (braces, brackets, colons અને commas), તેથી response compact રહે છે અને network પર ઝડપથી મોકલી શકાય છે. Mobile connections માટે આ મહત્વનું છે. JSON human-readable પણ છે; developer response જોઈને તરત સમજી અને debug કરી શકે છે, opaque binary formatની જેમ નહીં.

JSON objects દરેક languageના key-value maps જેવા છે અને arrays lists જેવી છે. Kotlin, JavaScript, Python અને Java જેવી લગભગ દરેક languageમાં JSON produce અને parse કરવા built-in અથવા સરળ support છે. તેથી API JSON return કરે તો કોઈ પણ languageમાં લખાયેલ client તેને consume કરી શકે છે. આ web servicesની interoperability માટે ખૂબ ઉપયોગી છે.

પહેલાં XML આ કામ માટે વપરાતું હતું, પરંતુ તે વધુ verbose અને parse કરવામાં cumbersome છે. Web અને mobile apps વધતાં industry JSONના simpler અને lighter model તરફ ગઈ. Wire પર નાનું, માણસ માટે readable, machine માટે સરળ અને દરેક જગ્યાએ supported: આ combinationને કારણે JSON APIsનું de facto format બન્યું.

Summary

Key takeaways

  • APIs data JSON text તરીકે આપે છે, જેને appએ ઉપયોગ કરતા પહેલાં parse કરવું પડે છે.
  • JSONમાં objects { }, key-value pairs, arrays [ ], strings, numbers, booleans અને null હોય છે.
  • Androidનું org.json object માટે JSONObject(text) અને list માટે JSONArray આપે છે.
  • Fields typed gettersથી વાંચો: getString, getInt અને getBoolean; nested structure માટે getJSONObject અને getJSONArray વાપરો.
  • Pattern: container parse કરો, array મેળવો, 0થી length() સુધી loop કરો અને દરેક itemના fields extract કરો.
  • Getterને JSONના actual structure અને type સાથે match કરો; Gson/Moshi JSONને Kotlin data classesમાં map કરી શકે છે.
  • Memory hook: JSONObject અને JSONArray, array loop કરો અને typed gettersથી fields કાઢો.

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