Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access JSON Array without array name

I have a JSON object:

{
   "login_name":"hello@gmail.com",
   "login_pass":"abc123",
   "created_on":"2021-01-17 19:20:07",
   "user_id":"1",
   "active":"1"
}

I don’t know how to access it because it doesn’t have a name.
This is using Volley:

val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
    { response ->
        val obj = JSONObject(response.toString()) // this works and outputs the JSON object
        val test: JSONObject = obj.getJSONObject("login_name") // this doesn't work

        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
    },
    { error ->
        Toast.makeText(this@Login, "Error!", Toast.LENGTH_LONG).show()
    }
)

I also tried converting the Json object to an array but that didn’t work either…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Looked at:
Get JSONArray without array name, How can i write Android Json parsing without array name

EDIT:

val obj = JSONObject(response)

That didn’t work for me because:
None of the following functions can be called with the arguments supplied.
(String!) defined in org.json.JSONObject
((MutableMap<Any?, Any?>..Map<*, *>?)) defined in org.json.JSONObject
(JSONTokener!) defined in org.json.JSONObject

But after 2 days of trying, this worked… Didn’t think I could just do that

val test = response.getString("login_name")

>Solution :

response is indeed a jsonObject, you could use it without know its name:

String login_name= response.getString("login_name");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading