androidkotlin

How to get data from a json array without directly making reference to the array name


enter image description here

I'd quickly explain what's going on in the JSON data above;

I have a table called messages, with some messages having a common message_id column. I grouped the messages by message_id. the boxes in red are the message_id's which have children

Now onto the question;

is it possible to access the children of the various arrays of message_id, without actually using the message_id string?

i.e iterate over the arrays

while (i < array.length) {
    array[i]
}

if it's possible how can I do it?

Below is how I currently get the first array from the data object using the array id exactly

 val jsonObject = JSONObject(response)

                        if (!jsonObject.getBoolean("error")) {
                            //getting data array from json response object
                            val dataObject = jsonObject.getJSONObject("data")
                            Log.i("MessageFragment", "[][] data array " + dataObject)
                            val array = dataObject.getJSONArray("NzbyxhmodN")

                            var i = 0
                            while (i < array.length()) {
                                //getting wallet object from json array
                                val message = array.getJSONObject(i)

                                //adding the wallet to wallet list
                                messageList!!.add(Message(
                                        message.getInt("id"),
                                        message.getInt("sender_id"),
                                        message.getInt("receiver_id"),
                                        message.getString("subject"),
                                        message.getString("message"),
                                        message.getString("message_id"),
                                        message.getString("timestamp"),
                                        message.getBoolean("isRead")
                                ))
                                i++
                            }

I want to get the arrays without using the name i.e ("NzbyxhmodN")


Solution

  • Unfortunately, you cannot model without knowing the key value. In such cases, I use this approach. It will be useful to you.

    // data -> server json response
    Iterator keys = data.keys();
    while(keys.hasNext()) {
        // random key
        String key = (String)keys.next();
        // and value...
        JSONArray value = data.getJSONArray(key);
    }