【问题标题】:Moshi map nested JSON value to fieldMoshi 将嵌套的 JSON 值映射到字段
【发布时间】:2020-09-01 16:00:13
【问题描述】:

有没有办法将嵌套的 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 节点创建嵌套类更好的方法?

【问题讨论】:

    标签: android json kotlin retrofit2 moshi


    【解决方案1】:

    您可以使用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
    }
    

    【讨论】:

    • 感谢您的回答。我还必须使用 @ToJson 方法将 fromJson 包装到适配器中,并在 moshi builder 中注册此适配器
    • 我只是认为有一种方法可以自动完成。这个想法取自 MapStruct mapper for java example
    • 能否请您发布此@martaisty 的完整代码
    猜你喜欢
    • 1970-01-01
    • 2020-03-19
    • 2021-07-06
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 2021-06-16
    相关资源
    最近更新 更多