Search code examples
androidjsonkotlingsonretrofit

"empty String" when parse json into model class in android with kotlin


I am Android developer,

I am facing a problem while making an API call.

I am receiving a huge amount of data, making an API call, and I get the API call success, I can see the JSON response in the logcat.

Now I convert that JSON response to a model class. Then I faced a problem. I get an exception something like this. "empty String".

But my data is huge. I can't find where exactly the problem is.

Here is what I use

  • Retrofit - for API call
  • Gson - for converting and handling data

What have I tried?

ActivitiesApiRepository.searchActivities(object : retrofit2.Callback<JsonElement> {
    //...
    override fun onResponse(call: Call<JsonElement>, response: Response<JsonElement>) {
        val mResponse = Gson().fromJson(response.body(), MyModelClass::class.java)
    }
}
  • Second try
ActivitiesApiRepository.searchActivities(object : retrofit2.Callback<MyModelClass> {
    //...
    override fun onResponse(call: Call<MyModelClass>, response: Response<MyModelClass>) {
        val mResponse = response.body() as MyModelClass
    }
}
Every time I got the same exception empty String

Please any have solution how can I manage it?


Solution

  • This problem occurred when your model class does not match your raw json result normally. I guess a variable type is "empty string" on your raw json result, and "List type" or "custom class type" on your code. You can copy and paste your json result to the text editor and try formatting it, and you can see the formatted result. Focus on the empty string result, and verify in your code whether it's the correct type.