0

I read a yaml file to a map in kotlin (Map<String, Any>) this yaml file contains a list of strings, eks:

...
myStrings:
  - string1
  - string2
  - string3
...

I read the map as follows:

private fun readWithGson(jsonPath: String): Map<String, Any> {
    val bufferedReader = BufferedReader(FileReader(jsonPath))
    val gson = Gson()

    @Suppress("UNCHECKED_CAST")
    return gson.fromJson(bufferedReader, Map::class.java) as Map<String, Any>
}

When println(map), it contains:

...
myStrings=[string1,string2,string3]
...

How can get the array of strings?

map["myStrings"] as Array<String>

produces a java.lang.ClassCastException

4
  • Because it is an ArrayList and not an Array! Commented Oct 28, 2020 at 16:13
  • Use .toTypedArray(). Using as is for casting, not converting. Commented Oct 28, 2020 at 16:14
  • You've edited the question and suddenly the results are entire different than last time. What stands out is that you are using Gson, which expects a JSON format to parse a yaml file.. Not sure how that even works but you'll likely need a yaml parser like snakeYAML Commented Oct 29, 2020 at 9:18
  • I am sorry for editing the question... The provided answer did work. I noticed I had some code which was not changed, when I allready had started to edit the question... I forgot all about it... :( Commented Oct 30, 2020 at 11:00

1 Answer 1

1

It is stored as an (Array)List. So just get and use it as a List:

val myStrings = map["myStrings"] as List<String>

If you need to edit the list later on you can cast it to MutableList:

val myStrings = map["myStrings"] as MutableList<String>

If you really need it to be an Array, though for most cases you don't, you'll have to convert the List to an array:

val myStringsArray = myStrings.toTypedArray()
Sign up to request clarification or add additional context in comments.

Comments

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.