【问题标题】:Klaxon Parsing of Nested Arrays嵌套数组的 Klaxon 解析
【发布时间】:2018-04-15 10:54:42
【问题描述】:

我正在尝试用 Klaxon 解析 this file,一般情况下它进展顺利,但我完全没有成功解析 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) 
    }

我知道我将功能调用为任意数组,因此输出只是每次都打印我 java.lang.Object@blabla。不过,使用 Array 也失败了。

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

向新人致敬

【问题讨论】:

    标签: json intellij-idea kotlin klaxon


    【解决方案1】:

    这是我在 Kotlin 中做类似事情的方式。您可以将响应解析为 Klaxon JsonObject,然后访问“特征”元素以将所有数组对象解析为 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)
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-11
      • 2021-08-18
      • 1970-01-01
      • 2018-08-24
      • 2019-02-02
      • 2019-01-02
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      相关资源
      最近更新 更多