2

I've been trying to parse JSON from an url for hours now but I'm too stupid I guess
I have tried

val result = URL("http://date.jsontest.com/").readText()

but it crashes

java.net.MalformedURLException: no protocol: date.jsontest.com

I have tried Klaxon's library

fun parse(name: String) : Any? {    
    val cls = Parser::class.java
    return cls.getResourceAsStream(name)?.let { 
        inputStream -> return Parser().parse(inputStream)
    }
}    
val obj = parse("http://date.jsontest.com/") as JsonObject

but it also crashes

kotlin.TypeCastException: null cannot be cast to non-null type com.beust.klaxon.JsonObject

Can someone please write in Kotlin the simpliest way to parse data from this link http://date.jsontest.com/

3
  • stackoverflow.com/questions/44883593/… answers your question. Commented Jul 13, 2017 at 5:17
  • what am I supposed to do with this ?... Commented Jul 13, 2017 at 5:21
  • can you post your stacktrace? Commented Jul 13, 2017 at 5:23

1 Answer 1

1

Hard to say why you are getting an error. Since this line is correct and working.

val result = URL("http://date.jsontest.com/").readText()

For the parse method. It does not work, becase it expects path to a JSON file but is getting a URL String.

Simplest example using Klaxon would be this.

val result = URL("http://date.jsontest.com/").readText()
val parser: Parser = Parser()
val stringBuilder: StringBuilder = StringBuilder(result)
val json: JsonObject = parser.parse(stringBuilder) as JsonObject
println("Time : ${json.string("time")}, Since epoch : ${json.long("milliseconds_since_epoch")}, Date : ${json.string("date")}, ")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.