I have a string input of the following format:
[[10.5,125.7], [60.5, 25.6] ....]]
How can one parse something like this in Kotlin? This should end up as array of arrays of floats.
CodePudding user response:
For a List<List<Float>>:
val result = text
.removeSurrounding("[[", "]]").split("], [", "],[")
.map { it.split(",").map { s -> s.toFloat() } }
For an Array<Array<Float>>:
val result = text
.removeSurrounding("[[", "]]").split("], [", "],[")
.map { it.split(",").map { s -> s.toFloat() }.toTypedArray() }
.toTypedArray()
CodePudding user response:
This format is standard format of json array you can use moshi library for parse json to kotlin models:
val json = "[[10.5,125.7], [60.5, 25.6]]"
val moshi: Moshi = Moshi.Builder().add(CookieMoshiAdapter()).build()
val type = Types.newParameterizedType(List::class.java, List::class.java, Float::class.javaObjectType)
val adapter: JsonAdapter<List<List<Float>>> = moshi.adapter(type)
val list = adapter.fromJson(json)!!