Search code examples
stringlistkotlindata-conversion

Convert a String into a List in Kotlin


In kotlin, I receive from a server this list of geocoordinates as a string:

[[45.02498, 7.55163], [45.02527, 7.55167], [45.02556, 7.55172], [45.02564, 7.55173], [45.02582, 7.55175], [45.02582, 7.55188], [45.02585, 7.55202], [45.02593, 7.55213], [45.026, 7.55218]]

How can I create a List of Pairs starting from this string? I've seen that is possible to use Regex, but I've not really understood how to use it, expecially having to deal with a starting and ending square parenthesis.


Solution

  • The solution actually was very simple, and this is an instance of code. The string has been transformed into a JSONArray and through a for loop it's possible to have access to all the elements, extracting the desired data.

    val jsonArray = JSONArray(receivedText)
    
    for (i in 0 until jsonArray.length()) {
        val pairArray = jsonArray.getJSONArray(i)
        val latitude = pairArray.getDouble(0)
        val longitude = pairArray.getDouble(1)
    
        Log.d("description","Pair $i - Latitude: $latitude, Longitude: $longitude")