Brian Chu
Brian Chu

Reputation: 113

Correct annotated @ToJson function for Moshi

Can I use JsonQualifier to annotate Map<String, List<T1>>? What's wrong with my function annotated with @ToJson? Runtime throws IllegalArgumentException: No @ToJson adapter for java.util.Map<java.lang.String, java.util.List> annotated [@CheckMap()]

I was trying to parse something like this:

"A" : [
  {
    { "a": [ {T1}, {T1}, {T1} ] },
    { "b": [ {T1}, {T1} ] },
    { "c": [ {T1}, {T1} ] }
  },
  {
    { "d": [ {T1}, {T1} ] },
    { "e": [ {T1} ] },
    { "f": [ {T1}, {T1} ] }
  }
]

where a, b, c, d, e, f could be arbitrary name. I have to use adapter (compare to GSON, I can use alternate). T1 is a JSON map to a class.

@Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class CheckMap
...

@JsonClass(generateAdapter = true)
data class SomeElement(
    @CheckMap val s: Map<String, List<T1>>
)

...

class CheckMapAdapter {
    @FromJson
    @CheckMap
    fun fromJson(foo: Map<String, List<T1>>): Map<String, List<T1>> {
        return foo
    }

    @ToJson
    fun toJson(@CheckMap test: Map<String, List<T1>>): String {
        return "something"
    }
}

Upvotes: 0

Views: 246

Answers (1)

Eric Cochran
Eric Cochran

Reputation: 8574

The problem is that the Kotlin adapter method sees the parameter type as java.util.Map<java.lang.String, ? extends java.util.List<T1>>.

You need to add @JvmSuppressWildcards: @ToJson fun toJson(@CheckMap test: Map<String, @JvmSuppressWildcards List<T1>>): String

By the way, your adapter fromJson method looks circular, but I assume that was just a test.

Upvotes: 1

Related Questions