Moshi adapter creation failure: "requires explicit JsonAdapter to be registered"

Viewed 5648
 var wall= ArrayList<VKWall>()
    try {
         val response = r.getString("response") as String
        val moshi = Moshi.Builder().build()
        val type: Type = Types.newParameterizedType(
            ArrayList::class.java,
            VKWall::class.java
        )
        val jsonAdapter: JsonAdapter<ArrayList<VKWall>> = moshi.adapter(type)

        wall = jsonAdapter.fromJson(response)!!

    } catch (e: JSONException){}

    return wall

It can not create adapter. Debuger can`t execute this string and goes to exception of function over this code

val jsonAdapter: JsonAdapter<ArrayList<VKWall>> = moshi.adapter(type)

I`am trying to do everything like there https://github.com/square/moshi

Platform java.util.ArrayList<com.e.app.fragments.vk_tabs.WallFragment.DataPackage.VKWall> (with no annotations) requires explicit JsonAdapter to be registered


@Parcelize
@JsonClass(



   generateAdapter = true)
    data class VKWall (
      //  val UserName:String="",
       // val UserSurname:String="",
        @Json(name = "text")
        val Text:String="" ,
      //  val attachments: Attachments?,
      //  val copyright: String="",
      //  val repost: Repost? 
    ):Parcelable
    {


    }
1 Answers

The problem is in that moshi don't have adapter for yours class VKWall. To resolve this you could add KotlinJsonAdapterFactory that based on reflection:

val moshi = Moshi.Builder()
    // ... add your own JsonAdapters and factories ...
    .add(KotlinJsonAdapterFactory())
    .build()

Or you could use generated adapter like this:

// Annotate yours class @JsonClass(generateAdapter = true)
@JsonClass(generateAdapter = true)
class VKWall(
 ....
)

More documentation about this https://github.com/square/moshi#kotlin

More about yours problem https://www.zacsweers.dev/a-closer-look-at-moshi-1-9/

Now, for Kotlin classes, you either need to use code gen, KotlinJsonAdapterFactory, or supply your own custom JsonAdapter. This is a potentially dangerous change! In projects using code gen, there are cases where Kotlin classes could have (appeared to) Just Work™️ before if you forgot to annotate them with @JsonClass. These will fail at runtime now. If you're worried about this, I suggest using Moshi 1.9 only in debug builds for a period of time to tease these out before releasing production builds with it.

Related