Home > Mobile >  Access JSON Array without array name
Access JSON Array without array name

Time:02-10

I have a JSON object:

{
   "login_name":"[email protected]",
   "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...

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")

CodePudding user response:

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

String login_name= response.getString("login_name");

CodePudding user response:

You are all most doing it right. Ass i see you convert the object to a string, and thats why you cant access the data afterwards.

   val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
    { response ->
        val obj = JSONObject(response) // 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()
    }
)

Try this, without the toString() function on response.

  • Related