i am new to kotlin and i'm trying to call an api that has a array form ["value1","value2"] to display in my main activity textView and i keep getting this error java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $ can someone help i'm using kotlin
this is the Data Class:
data class ApiValuesItem(
val values:Array<String?>
)
this is my interface:
import retrofit2.Call
import retrofit2.http.GET
interface ApiInterface {
@GET("values")
fun getApiValue(): Call<ApiValuesItem?>
}
and this is what i wrote in the mainActivity:
class MainActivity : AppCompatActivity() {
companion object {
const val BASE_URL = "http://xx.xx.xx.xx/sfa/api/"
}
@SuppressLint("ResourceType")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
get_Api.setOnClickListener {
getApiValues()
}
}
private fun getApiValues() {
val retrofitBuilder = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.build()
.create(ApiInterface::class.java)
val retrofitData = retrofitBuilder.getApiValue()
retrofitData.enqueue(object : Callback<ApiValuesItem?> {
override fun onResponse(
call: Call<ApiValuesItem?>,
response: Response<ApiValuesItem?>
) {
val responseBody = response.body()!!
val myStringBuilder = StringBuilder()
for (ApiValues in responseBody){
myStringBuilder.append(ApiValues.values)
myStringBuilder.append(", ")
}
Api_Res.text = myStringBuilder
}
override fun onFailure(call: Call<ApiValuesItem?>, t: Throwable) {
Log.d("MainActivity","onFailure: "+t.message)
Api_Res.text = t.message
}
})
}
}
Your Json:
["value1","value2"]
This is actually json array of strings.
If you define like below, it will be expecting json object. In that object , it will be expecting String Array with key "values"
data class ApiValuesItem(
val values:Array<String?>
)
You model class will be mapped like this.
{"values":["value1","value2"]}
But your root is directly an array.
So instead of Callback<ApiValuesItem?>
you should make it as any Iterable<String>
. You can use arraylist like below.
Callback<ArrayList<String>?>
Call<ArrayList<String>?>
Response<ArrayList<String>?>