Bird
Raised Fist0
Android Kotlinmobile~20 mins

JSON parsing with Gson/Moshi in Android Kotlin - Mini App: Build & Ship

Choose your learning style10 modes available
Build: User List Screen
This screen fetches a JSON string of users and shows their names and emails in a list.
Target UI
-------------------------
| User List             |
-------------------------
| • John Doe           |
|   john@example.com   |
| • Jane Smith         |
|   jane@example.com   |
-------------------------
Parse a JSON string containing a list of users with 'name' and 'email' fields.
Use Gson or Moshi library for JSON parsing.
Display the users in a vertical scrollable list.
Each list item shows the user's name in bold and email below it.
Show a loading indicator while parsing.
Handle parsing errors gracefully by showing an error message.
Starter Code
Android Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp

class UserListActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      UserListScreen()
    }
  }
}

@Composable
fun UserListScreen() {
  // TODO: Add state for loading, error, and user list
  // TODO: Parse JSON string using Gson or Moshi
  // TODO: Show loading indicator while parsing
  // TODO: Show error message if parsing fails
  // TODO: Show list of users when parsing succeeds
}
Task 1
Task 2
Task 3
Task 4
Task 5
Task 6
Task 7
Solution
Android Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

class UserListActivity : ComponentActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContent {
      UserListScreen()
    }
  }
}

data class User(val name: String, val email: String)

@Composable
fun UserListScreen() {
  val jsonString = """[
    {\"name\": \"John Doe\", \"email\": \"john@example.com\"},
    {\"name\": \"Jane Smith\", \"email\": \"jane@example.com\"}
  ]"""

  var users by remember { mutableStateOf<List<User>?>(null) }
  var isLoading by remember { mutableStateOf(true) }
  var errorMessage by remember { mutableStateOf<String?>(null) }

  LaunchedEffect(Unit) {
    try {
      val listType = object : TypeToken<List<User>>() {}.type
      users = Gson().fromJson(jsonString, listType)
    } catch (e: Exception) {
      errorMessage = "Failed to parse JSON"
    } finally {
      isLoading = false
    }
  }

  Scaffold(
    topBar = {
      TopAppBar(title = { Text("User List") })
    }
  ) { paddingValues ->
    Box(modifier = Modifier
      .fillMaxSize()
      .padding(paddingValues)) {
      when {
        isLoading -> {
          CircularProgressIndicator(modifier = Modifier.align(androidx.compose.ui.Alignment.Center))
        }
        errorMessage != null -> {
          Text(
            text = errorMessage ?: "",
            color = MaterialTheme.colorScheme.error,
            modifier = Modifier.align(androidx.compose.ui.Alignment.Center)
          )
        }
        users != null -> {
          LazyColumn(modifier = Modifier.fillMaxSize()) {
            items(users!!) { user ->
              Column(modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)) {
                Text(text = user.name, fontWeight = FontWeight.Bold)
                Text(text = user.email)
              }
              Divider()
            }
          }
        }
      }
    }
  }
}

This solution uses the Gson library to parse a JSON string into a list of User data objects. We define a User data class with name and email fields matching the JSON keys.

In the UserListScreen composable, we keep track of three states: isLoading to show a loading spinner, errorMessage to show an error if parsing fails, and users to hold the parsed list.

We use LaunchedEffect to parse the JSON once when the screen loads. If parsing succeeds, we update users. If it fails, we set an error message.

The UI shows a top app bar with the title. Then it shows a loading spinner while parsing, an error message if parsing fails, or a scrollable list of users if parsing succeeds. Each user item shows the name in bold and the email below.

This approach cleanly separates loading, error, and success states and uses Compose best practices for state and UI updates.

Final Result
Completed Screen
-------------------------
| User List             |
-------------------------
| • John Doe           |
|   john@example.com   |
|-----------------------
| • Jane Smith         |
|   jane@example.com   |
-------------------------
When the screen opens, a loading spinner shows briefly.
Then the list of users appears with their names and emails.
If JSON parsing fails, an error message appears instead.
Stretch Goal
Add a Refresh button in the top app bar to re-parse the JSON and update the list.
💡 Hint
Use a Button or IconButton in the TopAppBar and trigger the parsing logic again on click.

Practice

(1/5)
1. What is the main purpose of using Gson or Moshi in Android Kotlin apps?
easy
A. To convert JSON text into Kotlin objects
B. To create user interfaces
C. To manage app navigation
D. To handle database queries

Solution

  1. Step 1: Understand JSON parsing role

    Gson and Moshi are libraries that help convert JSON strings into Kotlin objects for easier data handling.
  2. Step 2: Identify the correct purpose

    They do not create UI, manage navigation, or handle databases directly.
  3. Final Answer:

    To convert JSON text into Kotlin objects -> Option A
  4. Quick Check:

    JSON parsing = Convert JSON to objects [OK]
Hint: Gson/Moshi = JSON to Kotlin objects [OK]
Common Mistakes:
  • Thinking Gson/Moshi create UI components
  • Confusing JSON parsing with database handling
  • Assuming they manage app navigation
2. Which of the following is the correct way to define a Kotlin data class for this JSON?
{"name":"Alice","age":30}
easy
A. class Person(var name: String, var age: String)
B. data class Person(val name: String, val age: Int)
C. data class Person(name: String, age: Int)
D. data class Person(val name: String, val age: String)

Solution

  1. Step 1: Match JSON keys and types

    The JSON has keys "name" (String) and "age" (Int).
  2. Step 2: Check Kotlin data class syntax

    Correct syntax uses 'data class' with val properties and types matching JSON.
  3. Final Answer:

    data class Person(val name: String, val age: Int) -> Option B
  4. Quick Check:

    Data class with val and correct types = data class Person(val name: String, val age: Int) [OK]
Hint: Use val and exact types matching JSON keys [OK]
Common Mistakes:
  • Using var instead of val unnecessarily
  • Wrong property types (e.g., age as String)
  • Missing 'val' keyword in data class
3. Given this code snippet using Gson:
val json = "{\"name\":\"Bob\", \"age\":25}"
val person = Gson().fromJson(json, Person::class.java)
println(person.name)

What will be printed?
medium
A. null
B. 25
C. Person
D. Bob

Solution

  1. Step 1: Parse JSON to Person object

    Gson converts the JSON string into a Person object with name="Bob" and age=25.
  2. Step 2: Print the name property

    println(person.name) outputs the name value, which is "Bob".
  3. Final Answer:

    Bob -> Option D
  4. Quick Check:

    person.name = "Bob" [OK]
Hint: fromJson maps JSON keys to object properties [OK]
Common Mistakes:
  • Printing age instead of name
  • Expecting class name instead of property value
  • Assuming null if parsing fails
4. What is wrong with this Moshi parsing code?
val json = "{\"name\":\"Eve\", \"age\":28}"
val moshi = Moshi.Builder().build()
val adapter = moshi.adapter(Person::class.java)
val person = adapter.fromJson(json)
println(person?.name)

Assuming Person is a correct data class, why might this code fail at runtime?
medium
A. Person class is not a data class
B. JSON string is malformed
C. Missing Moshi Kotlin adapter for data class support
D. Using println instead of Log

Solution

  1. Step 1: Check Moshi setup for Kotlin data classes

    Moshi requires adding the KotlinJsonAdapterFactory to support Kotlin features like default values and nullability.
  2. Step 2: Identify missing adapter

    The code builds Moshi without .add(KotlinJsonAdapterFactory()), so parsing may fail or produce null.
  3. Final Answer:

    Missing Moshi Kotlin adapter for data class support -> Option C
  4. Quick Check:

    Moshi needs KotlinJsonAdapterFactory for data classes [OK]
Hint: Add KotlinJsonAdapterFactory to Moshi builder [OK]
Common Mistakes:
  • Not adding KotlinJsonAdapterFactory
  • Assuming JSON string is invalid
  • Confusing println with logging
5. You have this JSON array:
[{"id":1,"title":"Task 1"},{"id":2,"title":"Task 2"}]

How do you parse it into a Kotlin List<Task> using Gson, assuming data class Task(val id: Int, val title: String)?
hard
A. Use TypeToken() {}.type with Gson.fromJson
B. Call Gson.fromJson(json, Task::class.java)
C. Parse each JSON object manually with JSONObject
D. Use Gson.toJson(json, List::class.java)

Solution

  1. Step 1: Understand parsing JSON arrays

    Gson needs a Type object to parse generic types like List<Task>.
  2. Step 2: Use TypeToken to get List<Task> type

    TypeToken() {}.type provides the correct type for Gson.fromJson to parse the array.
  3. Final Answer:

    Use TypeToken() {}.type with Gson.fromJson -> Option A
  4. Quick Check:

    Use TypeToken for generic list parsing [OK]
Hint: Use TypeToken for lists with Gson [OK]
Common Mistakes:
  • Parsing array as single object
  • Manually parsing instead of using Gson
  • Using toJson instead of fromJson
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard