简体   繁体   English

Android Kotlin + Klaxon - 解析JSON根数组

[英]Android Kotlin + Klaxon - Parsing a JSON root array

I have a JSON asset with a root array: 我有一个带有根数组的JSON资产:

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

I'm trying to parse it using Klaxon. 我正在尝试使用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 java.lang.ClassCastException:com.beust.klaxon.JsonArray无法强制转换为com.beust.klaxon.JsonObject

What am I doing wrong? 我究竟做错了什么?

Found the answer in Klaxon's GitHub issue board: https://github.com/cbeust/klaxon/issues/87 在Klaxon的GitHub问题板上找到答案: https//github.com/cbeust/klaxon/issues/87

Array parsing is done via parseArray() , so the fix was: 数组解析是通过parseArray() ,所以修复是:

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. 值得一提的是,数组解析仅通过流API支持,而不是对象映射API。 So we are limited to either supplying an InputStream or a String as an argument. 因此,我们仅限于提供InputStreamString作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM