javaandroid-studiokotlinandroid-volleyklaxon

Use Volley and Klaxon in non-activity class


I am trying to make a class representing a table in a database.

data class MSettings(
var name: String?,
var value: String?,
var Description: String?)

I need to get data from api. I'm trying use Volley, but Volley need context. I havent access to context in non-activity Class. So, I added var context: Context. OK, it's working. My api return JSON: "{"name":"enable","value":"true","desc":"description"}" Now I want parse response JSON. I'm trying use Klaxon:

Klaxon().parse<MSettings>(response)

But I get error:

com.beust.klaxon.KlaxonException: Unable to instantiate MSettings with parameters [name: enable, value: true]

because I have MSettings(context,name,value,desc). I must choose between get data from API and parse JSON?

Maybe you have another idea how to do it all?

Fragment get data from Data Class. Data Class get data from API and return parsed JSON. I havent idea.

Sorry for my weak english. Thanks for advice


Solution

  • The reason for the error you see is that you have named your description field Description, not desc, which is the name used in the JSON response:

    {"name":"enable","value":"true","desc":"description"}" 
    

    So just change the name of your field Description into desc or add a @Json(name = "desc") before your Description field like this:

    data class MSettings(
    var name: String?,
    var value: String?,
    @JSON(name = "desc")
    var Description: String?)