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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.