5

I have a JSON asset with a root array:

[
  {
    "word": "word",
    "label": "label"
  },
  {
    "word": "word2",
    "label": "label2"
  }
]

I'm trying to parse it using Klaxon.

So far I have tried several methods:

val wordDict = Klaxon().parse<List<DictWord>>( activity.assets.open("dict.json") )

val wordDict = Klaxon().parse<Array<DictWord>>( activity.assets.open("dict.json") )

val wordDict = Klaxon().parse<JsonArray<DictWord>>( activity.assets.open("dict.json") )

Which either result in an empty list or an exception:

java.lang.ClassCastException: com.beust.klaxon.JsonArray cannot be cast to com.beust.klaxon.JsonObject

What am I doing wrong?

Vaiden
  • 15,728
  • 7
  • 61
  • 91

1 Answers1

9

Found the answer in Klaxon's GitHub issue board: https://github.com/cbeust/klaxon/issues/87

Array parsing is done via parseArray(), so the fix was:

val wordDict = Klaxon().parseArray<DictWord>( activity.assets.open("dict.json") )

It is worth mentioning that array parsing is only supported via the streaming API, not the object mapping API. So we are limited to either supplying an InputStream or a String as an argument.

Vaiden
  • 15,728
  • 7
  • 61
  • 91
  • Actually it worked for Object mapping too, it successfully mapped each element of the array to an object of the corresponding data class I've defined for it. – Mohyaddin Alaoddin Aug 11 '18 at 14:06
  • Seems to be a new feature. Do you have any doc supporting your new find? – Vaiden Aug 12 '18 at 07:23
  • I've just tried it like this `val WordDict = ArrayList(Klaxon().parseArray(jsonString))`, I had to pass the parsed data into an `ArrayList` because `parseArray` returns a `List` while I needed an `ArrayList`. – Mohyaddin Alaoddin Aug 12 '18 at 11:19