I am calling an API using RxJava and Retrofit and storing the data in data class of kotlin. While calling the api, an error is thrown : java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $.
Here is the code:
API JSON:
{
"facilities": [
{
"facility_id": "1",
"name": "Property Type",
"options": [
{
"name": "Apartment",
"icon": "apartment",
"id": "1"
},
{
"name": "Condo",
"icon": "condo",
"id": "2"
},
{
"name": "Boat House",
"icon": "boat",
"id": "3"
},
{
"name": "Land",
"icon": "land",
"id": "4"
}
]
},
{
"facility_id": "2",
"name": "Number of Rooms",
"options": [
{
"name": "1 to 3 Rooms",
"icon": "rooms",
"id": "6"
},
{
"name": "No Rooms",
"icon": "no-room",
"id": "7"
}
]
},
{
"facility_id": "3",
"name": "Other facilities",
"options": [
{
"name": "Swimming Pool",
"icon": "swimming",
"id": "10"
},
{
"name": "Garden Area",
"icon": "garden",
"id": "11"
},
{
"name": "Garage",
"icon": "garage",
"id": "12"
}
]
}
],
"exclusions": [
[
{
"facility_id": "1",
"options_id": "4"
},
{
"facility_id": "2",
"options_id": "6"
}
],
[
{
"facility_id": "1",
"options_id": "3"
},
{
"facility_id": "3",
"options_id": "12"
}
],
[
{
"facility_id": "2",
"options_id": "7"
},
{
"facility_id": "3",
"options_id": "12"
}
]
]
}
The data class for serialization:: (FacilitiesData.kt)
data class Facilities(
@SerializedName("facilities")
val facilities: List<Facility>
)
data class Facility(
@SerializedName("facility_id")
val facility_id: String?,
@SerializedName("name")
val name: String?,
@SerializedName("options")
val options: List<Options>
)
data class Options(
@SerializedName("name")
val name: String?,
@SerializedName("icon")
val icon: String?,
@SerializedName("id")
val id: String?
)
RxJava code to fetch the response:
private fun fetchFacilities() {
loading.value = true
disposable.add(
facilityService.getFacilities()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object: DisposableSingleObserver<List<Facilities>>() {
override fun onSuccess(value: List<Facilities>?) {
facilities.value = value
loadError.value = false
loading.value = false
}
override fun onError(e: Throwable?) {
Log.e("Error", e.toString())
loadError.value = true
loading.value = false
}
})
)
}
The interface to fetch the api: (FacilityApi)
interface FacilityApi {
@GET("/iranjith4/ad-assignment/db")
fun getFacilities() : Single<List<Facilities>>
}
Service class to call the service api (FacilityService)
class FacilityService {
@Inject
lateinit var api: FacilityApi
init {
DaggerApiComponent.create().inject(this)
}
fun getFacilities(): Single<List<Facilities>> {
return api.getFacilities()
}
}
What can be the possible reason for the error? Please let me know.
fun getFacilities() : Single<Facilities>. Your Facilities class is the root.