Moshi 将嵌套的 JSON 值映射到字段

Moshi map nested JSON value to field

有没有什么方法可以将嵌套的 JSON 值映射到字段而无需额外的 classes?我有 JSON 回复

{
    "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"
        ],
    }
}

但是从 apple_music 我只需要 url 值。所以我决定创建 Kotlin 数据 class 并尝试使用 @Json 注释

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

但是,这不起作用。 它在运行时抛出异常

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

下面的代码有效

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

data class AppleMusic(val url: String)

我有几个嵌套值,为它们创建额外的 classes 有点夸张了。有没有比为 apple_music 节点创建嵌套 class 更好的方法?

一种方法是使用 alternate type adapters using @JsonQualifier。例如:

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