Android Kotlin + Klaxon-解析JSON根数组 [英] Android Kotlin + Klaxon - Parsing a JSON root array
问题描述
我有一个带有根数组的JSON资产:
I have a JSON asset with a root array:
[
{
"word": "word",
"label": "label"
},
{
"word": "word2",
"label": "label2"
}
]
我正在尝试使用Klaxon对其进行解析.
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") )
导致空列表或异常:
java.lang.ClassCastException:com.beust.klaxon.JsonArray不能是 转换为com.beust.klaxon.JsonObject
java.lang.ClassCastException: com.beust.klaxon.JsonArray cannot be cast to com.beust.klaxon.JsonObject
我在做什么错了?
推荐答案
Found the answer in Klaxon's GitHub issue board: https://github.com/cbeust/klaxon/issues/87
数组解析是通过parseArray()
完成的,因此解决方法是:
Array parsing is done via parseArray()
, so the fix was:
val wordDict = Klaxon().parseArray<DictWord>( activity.assets.open("dict.json") )
值得一提的是,仅通过流API而不是对象映射API支持数组解析.因此,我们只能提供InputStream
或String
作为参数.
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.
这篇关于Android Kotlin + Klaxon-解析JSON根数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!