CodexBloom - Programming Q&A Platform

How to handle complex JSON responses in Retrofit with Kotlin Coroutines on Android 14?

👀 Views: 92 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-21
android retrofit kotlin-coroutines Kotlin

I'm working on a personal project and I'm deploying to production and I've searched everywhere and can't find a clear answer... I'm working on a project and hit a roadblock. I'm working on an Android 14 project where I'm using Retrofit to fetch a complex JSON response, but I'm encountering issues with parsing nested objects and handling nullable fields. My API returns a response like this: ```json { "data": { "user": { "id": "123", "name": "John Doe", "profile": { "age": 30, "email": "john.doe@example.com" }, "preferences": null }, "status": "success" } } ``` I have defined my data classes as follows: ```kotlin data class ApiResponse( val data: Data ) data class Data( val user: User ) data class User( val id: String, val name: String, val profile: Profile, val preferences: Preferences? ) data class Profile( val age: Int, val email: String ) data class Preferences( // fields for preferences ) ``` When I make the API call using coroutines, my `ApiResponse` seems to be parsed correctly, but I get a `KotlinNullPointerException` when I'm trying to access `user.preferences`. Here's the code for my Retrofit service: ```kotlin interface ApiService { @GET("/user/profile") suspend fun getUserProfile(): ApiResponse } ``` And this is how I'm calling it in my ViewModel: ```kotlin class UserViewModel(private val apiService: ApiService) : ViewModel() { private val _user = MutableLiveData<User>() val user: LiveData<User> get() = _user fun fetchUser() { viewModelScope.launch { try { val response = apiService.getUserProfile() _user.value = response.data.user } catch (e: Exception) { Log.e("UserViewModel", "Error fetching user profile", e) } } } } ``` I have checked the API response and confirmed that `preferences` can indeed be null. However, when I try to access it like this: ```kotlin user.value?.preferences?.someField ``` I get a crash with the message: `KotlinNullPointerException: Attempt to invoke virtual method '...' on a null object reference`. I want to ensure that I handle the null cases safely without causing crashes. What am I missing in my implementation, and how can I properly handle the nullable `preferences` field in my code? This is part of a larger service I'm building. Am I missing something obvious? I'm working in a Debian environment. I'm open to any suggestions. I recently upgraded to Kotlin latest. Am I missing something obvious?