Search code examples
jsonintellij-ideakotlinklaxon

Klaxon Parsing of Nested Arrays


Im trying to parse this file with Klaxon, generally its going well, except I am totally not succeeding in parsing that subarray of features/[Number]/properties/

So my thought is to get the raw string of properties and to parse it seperately with Klaxon, though I dont succeed in that either. Apart from that I took many other approaches as well.

My code so far:

  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) 
    }

I am aware that I am invoking features as an Array of Any, so the Output is just printing me java.lang.Object@blabla everytime. Though, using Array failes either.

Really spend hours in this, how would you go on this?

Regards of newbie


Solution

  • Here's how I did something similar in Kotlin. You can parse the response as a Klaxon JsonObject, then access the "features" element to parse all the array objects into a JsonArray of JsonObjects. This can be iterated over and cast with parseFromJsonObject<Haltestelle> in your example:

    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)
    }