2

Trying to handle the response from API in Android Studio by using Kotlin. When converting the response of server from string to json the null values are converted as "null". If the value is null I want it as null. How to solve this problem?

Volley portion of the code:

val stringRequest = StringRequest(Request.Method.GET, url,
                Response.Listener<String> { response ->
                jsonList = JSONArray(response) }

Response of the server:

[
    {
        "id": 213,
        "dummy": null
    }
]

Call as Json

jsonList.getJSONObject(0).get("dummy")

Result of call:

Result of call

As a result the below code will return "null" which is totally useless.

jsonList.getJSONObject(0).get("dummy")?.toSting()

2 Answers 2

3

You can use like

jsonList.getJSONObject(0).get("dummy")?:""

if the result value is null it return empty string,

and if you want to get null you should remove .toString()

Sign up to request clarification or add additional context in comments.

Comments

1

You can check

jsonList.getJSONObject(0).get("dummy") == JSONObject.NULL

It will hold true in your case

So you could do something like this

val dummy = jsonList.getJSONObject(0).get("dummy")
val dummyString = if (dummy == JSONObject.NULL) null else dummy.toString()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.