Reputation: 69
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/
Upvotes: 2
Views: 7228
Reputation: 4841
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")}, ")
Upvotes: 1