Suyash Chavan
Suyash Chavan

Reputation: 735

Json parsing with moshi

Can anyone please tell me why this is not working

Model class :

@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)!!
        }
    }
}

When parsing the following json

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

with

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)!!
        }
    }

gives instagramBusinessAccount null but if I don't use Custom field names with @Json i.e. replacing instagramBusinessAccount with instagram_business_account and profilePictureUrl with profile_picture_url, it works fine.

Upvotes: 3

Views: 1724

Answers (1)

Suyash Chavan
Suyash Chavan

Reputation: 735

I was missing .add(KotlinJsonAdapterFactory()) in Moshi Builder.

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

It works now.

Upvotes: 4

Related Questions