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

标签 android json kotlin retrofit2 moshi

有没有办法将嵌套的JSON值映射到字段而无需其他类?我有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数据类,并尝试了带有@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)

我有几个嵌套的值,并且为它们创建额外的类非常麻烦。除了为apple_music节点创建嵌套类之外,还有什么更好的方法吗?

最佳答案

一种方法是使用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
}

关于android - Moshi将嵌套的JSON值映射到字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61825805/

相关文章:

android - Fragment 的 onCreateView() 方法中的 NullPointerException

c# - Newtonsoft.Json 自定义日期序列化

android - 使用GSON反序列化嵌套数组

javascript - JSON透视图

java - 如何修复 'Cannot access database on the main thread since it may potentially lock the UI for a long period of time.'

android - Admobs 需要我已经拥有的权限

java - 像 Uber Android 一样在 map 上旋转标记和移动动画

java - 创建一个 C++ 静态库以在 Android 上与 Java 一起使用

kotlin - for范围中的 `val`不是不可变的?

kotlin - 如何使用runBlocking等待CoroutineScope完成