json - 嵌套数组的 Klaxon 解析

标签 json intellij-idea kotlin klaxon

我正在尝试解析 this file使用 Klaxon,一般情况下进展顺利,除了我完全没有成功解析 features/[Number]/properties/

所以我的想法是获取原始属性字符串并使用 Klaxon 单独解析它,尽管我也没有成功。除此之外,我还采用了许多其他方法。

到目前为止我的代码:

  class Haltestelle(val type: String?, val totalFeatures: Int?, val features: Array<Any>?)

fun main(args: Array<String>) { // Main-Routine


    val haltejsonurl = URL("http://online-service.kvb-koeln.de/geoserver/OPENDATA/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=ODENDATA%3Ahaltestellenbereiche&outputFormat=application/json")
    val haltestringurl = haltejsonurl.readText()


    val halteklx = Klaxon().parse<Haltestelle>(haltestringurl)


    println(halteklx?.type)
    println(halteklx?.totalFeatures)
    println(halteklx?.features)

    halteklx?.features!!.forEach {
        println(it) 
    }

我知道我正在调用作为 Any 数组的功能,所以输出只是每次打印 java.lang.Object@blabla。但是,使用 Array 也会失败。

真的要花几个小时在这上面,你会怎么做?

新人问候

最佳答案

以下是我在 Kotlin 中执行类似操作的方法。您可以将响应解析为 Klaxon JsonObject,然后访问“features”元素以将所有数组对象解析为 JsonObjects 的 JsonArray。这可以在您的示例中迭代并使用 parseFromJsonObject 进行转换:

import com.beust.klaxon.JsonArray
import com.beust.klaxon.JsonObject
import com.beust.klaxon.Parser
import com.github.aivancioglo.resttest.*

val response : Response = RestTest.get("http://anyurlwithJSONresponse")
val myParser = Parser()
val data : JsonObject = myParser.parse(response.getBody()) as JsonObject
val allFeatures : JsonArray<JsonObject>? = response["features"] as JsonArray<JsonObject>?

for((index,obj) in allFeatures.withIndex()) {
    println("Loop Iteration $index on each object")
    val yourObj = Klaxon().parseFromJsonObject<Haltestelle>(obj)
}

关于json - 嵌套数组的 Klaxon 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49841123/

相关文章:

intellij-idea - Gradle DSL 方法未找到 : 'compileOnly()'

android-studio - Android Studio Kotlin 编译器警告

java - Toast 数组值不起作用

javascript - 我如何进行部分更新或其他方法来更新 PouchDb 中的复杂文档?

java - 在 IntelliJ 文件搜索中忽略大文件

android - 删除在闭包内创建的实时数据 Observer

android - 使用 Kotlin 将原生广告添加到 Flutter 项目

javascript - 在 Knockout JS 中延迟加载

php - 如何在android中比较JSON对象和字符串?

java - IntelliJ插件: Navigate from Project View to a file without triggering AutoScrollFromSource?