Json разбор с моши - PullRequest
       11

Json разбор с моши

0 голосов
/ 27 февраля 2019

Может кто-нибудь сказать, пожалуйста, почему это не работает

Класс модели:

@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, все работает нормально.

1 Ответ

0 голосов
/ 27 февраля 2019

Мне не хватало .add (KotlinJsonAdapterFactory ()) в Moshi Builder.

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

Теперь работает.

...