mamenejr
mamenejr

Reputation: 325

Retrieve specific field in JSON

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?

Upvotes: 1

Views: 849

Answers (2)

Artem Kuznetsov
Artem Kuznetsov

Reputation: 1

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?
}

Upvotes: 0

Ashish
Ashish

Reputation: 6919

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

Upvotes: 1

Related Questions