Based on your code, I'm going to assume you've completely parsed it into a Map<K, V>
. If you have, the reason is extremely easy to find: You've added an Array(/List) to an Array. Which means your attempt gives you an Array<Array<String>>
or Array<List<String>>
.
If you again take a look at your code, you only add one item, or one array to the array. If you parse it back to JSON, it looks like this:
[
[
"0", "3.00", ...
]
]
Basing off the JSON example, here's a pseudocode-ish example of your current code:
[
[
"0", "3.00", ...
]
].size()
Which naturally returns 1: you only have one item in the parent.
If you wanted it to work exactly the way you currently have it, you'd have to use the spread operator (*
). arrayOf
takes a vararg
, and you have to spread the original array to the vararg to not pass an array. That lands you with an Array<String>
(or possibly Array<Any>
depending on the map):
arrayOf(*responseModel.schedule.get("0")).count()
I do not recommend this approach - it's overkill in your case, and will reduce performance. I'm mentioning it because it's a solution.
As Boken has already mentioned, you don't need to wrap it in an Array at all. If you store it as a Map, you already have a List or Array and you can access it incredibly simply with responseModel.schedule.get("0").size
.
If you store it as Any
(which I assume you do), you'll have to add an additional step:
val cache = responseModel.schedule.get("0"); // Any, in reality Array<String>/Array<Any>/List<Any>/List<String>
if (cache is Array) println(cache.size)
else if(cache is List) println(cache.size)
The casting here is to get automatic type inference - if you have an Any
, the compiler doesn't know if it has a size
field, and it will therefore throw an exception.
You can, of course, cast it directly, but that isn't a good idea if you ever end up with different input (intentionally or accidentally)
If, however, you don't actually store it in the form of a map, that complicates matters. To keep up with the first part, you'd have an Array<JSONObject>
, and you only have one JSONObject in the array.
Unlike the last part, you can't use the spread operator and get it straight into an Array
(which, again, I don't recommend you use unless you have to)
If you store a JSONObject for whatever system you use, it might have a size/length field/function that you can use, and it's not as complicated. Otherwise, you'll need to get an array/list from the JSON object, and run the length on that. I'd show you code for this part, but without knowing what you use (built-in, Jackson, Gson, etc), I don't have enough details to show any code. Nevertheless, the idea is still getting the size directly from the JSONObject, or getting an Array which you can run the size on instead.
Further reading