android - 用moshi解析json

标签 android json moshi

谁能告诉我为什么这不起作用

模型类:

@JsonClass(generateAdapter = true)
data class InstagramBusinessAccountResponse(
        val data : List<Account>
) {
    data class Account(
            @Json(name = "id") val id : String,
            @Json(name = "instagram_business_account") val instagramBusinessAccount : InstagramBusinessAccount
    ) {
        data class InstagramBusinessAccount(
                @Json(name = "id") val id: String,
                @Json(name = "name") val name: String,
                @Json(name = "profile_picture_url") val profilePictureUrl: String = ""
        )
    }

    companion object {
        fun fromJson(json: String) : InstagramBusinessAccountResponse {
            val moshi = Moshi.Builder().build()
            val jsonAdapter = moshi.adapter(InstagramBusinessAccountResponse::class.java)

            return jsonAdapter.fromJson(json)!!
        }
    }
}

解析如下json时

{"data":[{"instagram_business_account":{"id":"id","username":"name","name":"Suyash Chavan","profile_picture_url":"image"},"id":"id"}]}

InstagramBusinessAccountResponse.fromJson(json.toString())

...

companion object {
        fun fromJson(json: String) : InstagramBusinessAccountResponse {
            val moshi = Moshi.Builder().build()
            val jsonAdapter = moshi.adapter(InstagramBusinessAccountResponse::class.java)

            return jsonAdapter.fromJson(json)!!
        }
    }

给 instagramBusinessAccount null 但如果我不将自定义字段名称与 @Json 一起使用,即将 instagramBusinessAccount 替换为 instagram_business_account 并将 profilePictureUrl 替换为 profile_picture_url,它工作正常。

最佳答案

我在 Moshi Builder 中缺少 .add(KotlinJsonAdapterFactory())。

val moshi = Moshi.Builder()
                    .add(KotlinJsonAdapterFactory())
                    .build()

现在可以了。

关于android - 用moshi解析json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54900155/

相关文章:

java - 使用 moshi 格式化 json

android - 安卓中的 Moshi vs Gson

android - 您可以使用 native 应用程序做什么,而您不能使用混合应用程序

android - 无法在 Android 中使用 SQLite 的 DATE 列上的 WHERE 检索数据库记录

android - android 中的 CountDownTimer - 如何重新启动它

Android - 使用 Retrofit 获取错误 "Cannot construct instance of (although at least one create exist)"

android - 如何在通知上显示计时器?

javascript - angularjs中过滤表的列数据

json - NodeJS + Mongo - 如何获取集合的内容?

java - 解析作为对象或对象数组的 JSON 键