Server JSON Data display in activity using Retrofit. JSON data convert through gson.
Gives Error: "java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $"
JSON Format :
{"success":1,"company":[{"Cmp_Id":"1","Cmp_Name":"ABC","GSTIN":"AAAA"}]}
Code:
class Company {
//@SerializedName("Cmp_Id")
var Cmp_Id : Int = 0
//@SerializedName("success")
//val success : String = ""
//@SerializedName("Cmp_Name")
var Cmp_Name : String? = ""
//@SerializedName("GSTIN")
var GSTIN : String? = ""
}
class CompanyList {
val success : String = ""
lateinit var company : ArrayList<Company>
}
interface APIInterface {
@GET("Company.php")
fun getCompanyData() : Observable<List<CompanyList>>
}
object APIClient {
val BASE_URL = "http://10.0.2.2/"
var retrofit:Retrofit? = null
val apIClient:Retrofit?
get() {
if (retrofit == null)
{
retrofit = Retrofit.Builder().
baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
}
return retrofit
}
}
MainActivity.kt
private fun fetchData(){
/* compositeDisposable.add(api.getCompanyData()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { companyList-> displayData(companyList)
}
)*/
val retrofit = APIClient.apIClient
if (retrofit != null) {
api = retrofit.create(APIInterface::class.java)
}
api.getCompanyData()
.subscribeOn(Schedulers.io())
.unsubscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ companyAdapter.setCompany(it.component1().company)
},{
Toast.makeText(applicationContext, it.message, Toast.LENGTH_SHORT).show()
})
}
The retrofit interface:
interface APIInterface {
@GET("Company.php")
fun getCompanyData() : Observable<List<CompanyList>>
}
Hints retrofit that you expect a list of CompanyList. However, the json you receive is a single CompanyList. This is what the gson error your getting tells you - Expected to begin with an array but it was an object.
Changing the retrofit interface to:
interface APIInterface {
@GET("Company.php")
fun getCompanyData() : Observable<CompanyList>
}
will hint retrofit that you expect a single object of type CompanyList and this should work for the json you've posted.