2

I am fairly new to Kotlin and I am currently dealing with JSON a lot.

I receive a JSON string from the server which I parse into JSONArray as below

var dataArray = JSONArray(String(resultVar!!))

But as far as I've seen JSONArray doesn't really give me enough capabilities to change it's data, it forces me to create a new JSONArray, if I'm not mistaken. So I thought I should use MutableList<JSONObject>, which seems good enough, but I can't find a way to parse JSONArray or the String into it.

How do I do this the easy way? Do I have to iterate through the JSONArray adding every single JSONObject one by one?

As a side question, should I just stick to JSONArray? Is there a way to manipulate the data inside it?

Aegletes
  • 460
  • 2
  • 6
  • 17

1 Answers1

6

As far as it seems, there is no builtin method to convert JSONArray to List. However, You can use Kotlin tricks to make the java code much shorter:

fun JSONArray.toMutableList(): MutableList<JSONObject> = MutableList(length(), this::getJSONObject)

Note that JSONArray may have values that are not JSONObject (but JSONArray for example). If you are not sure the array contains just object, use the following method:

fun JSONArray.toMutableList(): MutableList<Any> = MutableList(length(), this::get)

If you are using the JSON-java library and not the android one, then you can use JSONArray.toList() which returns a list you can modify.

Yoav Sternberg
  • 6,421
  • 3
  • 28
  • 30