1

I have a data class which represents the object I'm receiving from my API :

data class MyObject(
    @SerializedName("id") var id: Int,
    @SerializedName("status.description") var status: String
)

This is what my JSON looks like :

{
    "id": 1,
    "status": {
        "description": "OK"
    }
}

I'm fetching these data with Retrofit using Gson adapter but I always have my status attribute to null. Even if I use Moshi it's still null.

How can I get this attribute from my JSON without having to create a class Status with only one and a unique attribute named description?

mamenejr
  • 305
  • 9
  • 17
  • There is a cool lib for json processing out there, tutorial: https://www.baeldung.com/kotlin-json-klaxson#json-path-query-api – Nobody Jan 23 '20 at 09:32

2 Answers2

1

Try this :

data class MyObject(
    @SerializedName("id") var id: Int,
    @SerializedName("status") var status: Status
)

data class Status(
    @SerializedName("description") var description: String,
)

if you don't want above method :

https://stackoverflow.com/a/23071080/10182897

Ashish
  • 6,791
  • 3
  • 26
  • 48
  • 1
    In addition to this correct answer, you can omit using @SerializedName annotation if the field has the same name as Json field – Samir Spahic Jan 23 '20 at 10:52
0
data class MyObject(
    val id: Int,
    val status: Status
)

data class Status(
    val description: String
)

You can use val to make thiese fields final. Also one trick to keep in mind, if you use final fields, kotlin is able to make a smartcast for you.

Example:

data class Status(
    val description: String?
)

val status: Status = Status("success")
if ( status.description != null){
  // status.description will be smartcasted to String, not String?
}