martaisty
martaisty

Reputation: 33

Moshi map nested JSON value to field

Is there any way to map nested JSON value to field without additional classes? I have a JSON response

{
    "title": "Warriors",
    "artist": "Imagine Dragons",
    "apple_music": {
        "url": "https://music.apple.com/us/album/warriors/1440831203?app=music&at=1000l33QU&i=1440831624&mt=1",
        "discNumber": 1,
        "genreNames": [
            "Alternative",
            "Music"
        ],
    }
}

But from apple_music I need only url value. So I decided to create Kotlin data class and tried option with @Json annotation

data class Song(
    val title: String,
    val artist: String,
    @Json(name = "apple_music.url")
    val appleMusicUrl: String
)

However, this doesn't work. It throws an exception at runtime

Required value 'appleMusicUrl' (JSON name 'apple_music.url') missing at $

The code below is working

data class Song(
    val title: String,
    val artist: String,
    @Json(name = "apple_music")
    val appleMusic: AppleMusic
)

data class AppleMusic(val url: String)

I have several nested values and creating extra classes for them is quite overblowing. Is there any better ways than creating nested class for apple_music node?

Upvotes: 2

Views: 1920

Answers (1)

Sandi
Sandi

Reputation: 2731

One way you can do this is with alternate type adapters using @JsonQualifier. For example:

@Retention(RUNTIME)
@JsonQualifier
annotation class AppleMusicUrl

data class Song(
    val title: String,
    val artist: String,
    @AppleMusicUrl
    val appleMusicUrl: String
)

@FromJson
@AppleMusicUrl
fun fromJson(json: Map<String, Any?>): String {
    return json.getValue("url") as String
}

Upvotes: 1

Related Questions