首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用moshi进行Json解析

使用moshi进行Json解析
EN

Stack Overflow用户
提问于 2019-02-27 15:27:29
回答 1查看 1.1K关注 0票数 3

有没有人能告诉我为什么这个不起作用

模型类:

代码语言:javascript
复制
@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时

代码语言:javascript
复制
{"data":[{"instagram_business_account":{"id":"id","username":"name","name":"Suyash Chavan","profile_picture_url":"image"},"id":"id"}]}

使用

代码语言:javascript
复制
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空值,但是如果我不使用@Json的自定义字段名,比如用instagram_business_account替换instagramBusinessAccount,用profile_picture_url替换profilePictureUrl,它就能正常工作。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-27 16:16:00

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

代码语言:javascript
复制
val moshi = Moshi.Builder()
                    .add(KotlinJsonAdapterFactory())
                    .build()

它现在起作用了。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54900155

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档