android – Extract json object value using Gson-ThrowExceptions

Exception or error:

Suppose the web api return a json object like this.

{
  "something": "value"
}

Then I using Gson to convert it to local class.

webRequest.enqueue(object : Callback<WebResponse> {

    override fun onFailure(call: Call<WebResponse>, t: Throwable) {
        // Log.e(TAG, "Failed", t)
    }

    override fun onResponse(call: Call<WebResponse>, response: Response<WebResponse>) {
        // Extracting the value from something in json object
    }
})

I define the local class, but not know how to use it.

class WebResponse(
    @SerializedName("something")
    var something: String? = ""
)
How to solve:

Try this

If you use LiveData,

private val _webResponse = MutableLiveData<WebResponse>()
val webResponse: LiveData<WebResponse>
    get() = _webResponse

// Your request
webRequest.enqueue(object : Callback<WebResponse> {

    override fun onFailure(call: Call<WebResponse>, t: Throwable) {
        // Log.e(TAG, "Failed", t)
    }

    override fun onResponse(call: Call<WebResponse>, response: Response<WebResponse>) {
        // Extracting the value from something in json object
        if (response.isSuccessful()) {
           _webResponse.value = response.body()
        }
    }
})

// You can use above live data as follow
webresponse.observe(viewLifecycleOwner, Observer {
    if (it != null) {
        // Do something with your `WebResponse` object
        val something = it.something!!
    }
})

Leave a Reply

Your email address will not be published. Required fields are marked *