Issue
I've read through multiple posts on StackOverflow, but haven't found a solution that fits my problem yet. Could you please help me fix this Retrofit error?
JSON response:
{
"products": [
{
"barcode_number": "8000040000802",
"barcode_type": "EAN",
"barcode_formats": "EAN 8000040000802",
"mpn": "",
"model": "",
"asin": "",
"product_name": "Campari Bitter 25% Vol. 1 L",
"title": "",
"category": "Food, Beverages & Tobacco > Beverages > Alcoholic Beverages > Bitters",
"manufacturer": "Campari",
"brand": "Campari",
"label": "",
"author": "",
"publisher": "",
"artist": "",
"actor": "",
"director": "",
"studio": "",
"genre": "",
"audience_rating": "",
"ingredients": "",
"nutrition_facts": "",
"color": "",
"format": "",
"package_quantity": "",
"size": "",
"length": "",
"width": "",
"height": "",
"weight": "",
"release_date": "",
"description": "",
"features": [],
"images": [
"https://images.barcodelookup.com/19631/196313718-1.jpg"
],
"stores": [
{
"store_name": "Rakuten Deutschland GmbH",
"store_price": "16.50",
"product_url": "https://www.rakuten.de/produkt/campari-bitter-25-vol-1-l-1826679605",
"currency_code": "EUR",
"currency_symbol": "€"
}
],
"reviews": []
}
]
}
Data classes that have been created by the JSON to Kotlin plugin:
data class BaseResponse(
val products: List<Product>
)
Product:
data class Product(
val actor: String,
val artist: String,
val asin: String,
val audience_rating: String,
...
)
Store:
data class Store(
val currency_code: String,
val currency_symbol: String,
val product_url: String,
val store_name: String,
val store_price: String
)
Service:
interface BarcodeLookupApiService {
@GET("products")
suspend fun getArticleData(@Query("barcode") barcode: String,
@Query("key") key: String): List<BaseResponse>
}
Retrofit Builder:
object RetrofitBuilder {
private const val BASE_URL = "https://api.barcodelookup.com/v2/"
private fun getRetrofit(): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val apiService: BarcodeLookupApiService =
getRetrofit().create(BarcodeLookupApiService::class.java)
}
Are the data classes created by the plugin not right? Or should my service not return a list? I've tried returning a simple BaseResponse object but that doesn't work either.
Solution
Change your interface as shown below:
interface BarcodeLookupApiService {
@GET("products")
suspend fun getArticleData(@Query("barcode") barcode: String,
@Query("key") key: String): BaseResponse
}
and to get list of products do as shown below:
baseRespose.ProductsList
This will fix your issue. The response is an object with has an array inside object. Hence you are getting error.
Answered By - Keshav1234
Answer Checked By - Cary Denson (JavaFixing Admin)