0

I need to get the last element in a JSONObject, to retrieve the object my code is:

val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null,
            Response.Listener { response ->
                Log.i("response", "Response: %s".format(response.toString()))

                var jsona: JSONObject = response.getJSONObject("daily")

            },
            Response.ErrorListener { error ->
                Log.i("error", "Error: %s".format(error.toString()))
            }
        )

And so I acquire the daily value with the jsona variable

{"1582934400000":12450,"1583020800000":12639,"1583107200000":12439,"1583193600000":12348,"1583280000000":12278,"1583366400000":12322,"1583452800000":12435}

Is there an intelligent way to parse this data to find the value ("1583452800000":12435) or more preferably the 12435?

It seems like I can only access data within the object by knowing the string, but the string should change and I only ever need that last data point.

Getting the element with the biggest key (also last data point):

var top: Long = 0
for (key in jsona.keys()){
            if (key.toLong() > top) {
            top = key.toLong()
      }
}

Then accessing it with

jsona.get(top.toString())

Just was hoping for a more efficient solution.

Jenea Vranceanu
  • 4,530
  • 2
  • 18
  • 34
Kippet
  • 89
  • 1
  • 9
  • 1
    Relying on the property order in a JSON object is controversial (See, for example, https://stackoverflow.com/q/30076219/4636715). So, do you have a better logic than being *positionally last*. like *the key with lowest/highest numeric value*? – vahdet Aug 27 '20 at 06:34
  • Yes, it would always be the key with the highest value. – Kippet Aug 27 '20 at 06:36
  • If you are/API team constructing this JSON, than you should create array of elements. So you can get last element easily. – Naitik Soni Aug 27 '20 at 06:56

2 Answers2

0

I have tested successfully with below codes:

    int result = 0;
    String json = "{ \"1582934400000\": 12450, \"1583020800000\": 12639, \"1583452800000\": 12435}";
    try {
        JSONObject convertedObject = new JSONObject(json);
        Iterator<?> keys = convertedObject.keys(); 
        while (keys.hasNext()) {
            result = convertedObject.getInt((String) keys.next()); //result is 12435
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

You could refer it.

navylover
  • 12,383
  • 5
  • 28
  • 41
0
try {
    String json = "{ \"1582934400000\": 12450, \"1583020800000\": 12639, \"1583452800000\": 12435}";
    JSONObject obj = new JSONObject(json);

    Iterator<String> keyItr = obj.keys();
    String lastValue="";

    while(keyItr.hasNext()) {
        String key = keyItr.next();
        lastValue = obj.getString(key);
    }

    Log.d("last val=",lastValue);

} catch (JSONException e) {
    e.printStackTrace();
}

Can be the other way.

Naitik Soni
  • 700
  • 8
  • 16