谁能告诉我为什么这不起作用
模型类:
@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/