Parsing a jsonrray into object using moshi with Retrofit and Kotlin

Viewed 4241

I am trying to parse using Moshi Library for JSON Array using Kotlin Coroutines .

Code use

 fun retrofitIndia(baseUrl : String) : Retrofit = Retrofit.Builder()
        .client(clientIndia)
        .baseUrl(baseUrl)
        .addConverterFactory(MoshiConverterFactory.create())
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .build()

I get issue while Parsing the data class for JSON Array . I have used same for JSON Object and it works fine but during array , it crashes Below is the crash line

java.lang.IllegalArgumentException: Unable to create converter for java.util.ArrayList<data.india.Delta2>

I call from Globallaunch coroutine where it gets failed

Code :

 GlobalScope.launch(Dispatchers.Main) {
            val statsRequest = i.getStats()
            try {
                val response = statsRequest.await()
               if(response.){
                    val statsResponse = response.body() //This is single object Tmdb Movie response


                    Log.i("stats",""+statsResponse)
                }else{
                    Log.d("MainActivity ",response.errorBody().toString())
                }
            }catch (e: Exception){
                Log.e("Exception",e.localizedMessage)
            }
        }
2 Answers

You should make the type just List<T>, Moshi only supports the collection interfaces, not the concrete collection classes like ArrayList<T>, LinkedList<T>, etc.. The same goes for other kinds of collections: use Set<T> instead of HashSet<T>, and Map<K, V> instead of HashMap<K, V>, etc..

I don't think the coroutines have anything with the parsing error, try following Reading Json lists using Moshi

Quick snippet will look something like:

// Single item declaration 
class SingleListItem(val title: String, val number: Int)

private var listMyData = Types.newParameterizedType(MutableList::class.java, SingleListItem::class.java)
private val adapter: JsonAdapter<List<SingleListItem>> = Moshi.Builder().add(KotlinJsonAdapterFactory()).build().adapter(listMyData)
Related