gpt4 book ai didi

android - 用moshi解析json

转载 作者:行者123 更新时间:2023-11-29 18:34:19 25 4
gpt4 key购买 nike

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

模型类:

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com