'How can I access Data Class Properties created from JSON in Kotlin/Android

I am just getting started with Android/Kotlin and I am having issues with something very basic. I use retrofit to return JSON:

[
  {
    "id": "45837",
    "date_time": "2022-02-02 12:50:06",
    "pool_filter_status": "0",
    "pool_temperature": "97.59",
    "target_temperature": "97.3",
    "status_changed": "1"
  }
]

In my viewmodel class, I have the following function that does retrieve the code from the server:

...

   private val _pooldata = MutableLiveData<List<PoolData>>()
   val pooldata: LiveData<List<PoolData>> = _pooldata

...

private fun getPoolData() {
        
        viewModelScope.launch {
            _status.value = PoolApiStatus.LOADING
            try {
                _pooldata.value = PoolDataApi.retrofitService.getPoolData()
                _status.value = PoolApiStatus.DONE
            } catch (e: Exception) {
                _status.value = PoolApiStatus.ERROR
     
            }
     
        }
     
    }

For what its worth, its always just a single JSON object (though its in a single element array)

My really dumb question is how to access the properties of the data object / returned JSON.

If I log _pooldata.value.toString(), I just get:

[PoolData(id=45833, date_time=2022-02-02 12:30:02, pool_filter_status=1, pool_temperature=96.91, target_temperature=97.3, status_changed=0)]

I am just trying to understand Kotlin "by doing" at this point, but I don't understand how to access those values (id, date_time, etc). its not _pooldata.id.value, _pooldata[0].id.value etc.

The data class is setup as:

data class PoolData(
    val id: String,
    val date_time: String,
    val pool_filter_status: String,
    val pool_temperature: String,
    val target_temperature: String,
    val status_changed: String
)

Thanks.



Solution 1:[1]

You need to create two classes. First for the array and second for the JSON object which is present in the array.

For array

class Data : ArrayList<DataItem>()
//Ignore class name

For JSON object

data class DataItem(
    val date_time: String,
    val id: String,
    val pool_filter_status: String,
    val pool_temperature: String,
    val status_changed: String,
    val target_temperature: String
)

If you don't want to create the data class on your own then in the android studio there is a plugin named JSON to Kotlin class.

Visit this link to know more https://www.instagram.com/p/CW7UNzZj0gv/

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 yash1307