Skip to content

Instantly share code, notes, and snippets.

@TJC
Created August 16, 2018 11:15
Show Gist options
  • Select an option

  • Save TJC/74c8f39cd196dda3a755c6eb4f6ddb97 to your computer and use it in GitHub Desktop.

Select an option

Save TJC/74c8f39cd196dda3a755c6eb4f6ddb97 to your computer and use it in GitHub Desktop.
Super basic Kotlin example with JSON
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.2.60"
application
}
application {
mainClassName = "HelloKt"
}
group = "net.dryft"
version = "1.0-SNAPSHOT"
repositories {
mavenCentral()
jcenter()
}
dependencies {
compile(kotlin("stdlib-jdk8"))
implementation("com.beust:klaxon:3.0.1")
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}
// src/main/kotlin/Hello.kt
import com.beust.klaxon.Klaxon
fun main(args: Array<String>) {
println("Hello Kotlin!")
var item = Klaxon().parse<LineItem>(exampleJson())
// parse can return null, so you have to refer to item with the null-safety operator:
println("Nice ${item?.itemId} you've got there")
item = null
println("Bad ${item?.itemId} you've got there")
}
data class LineItem(val itemId: String, val price: Float)
fun exampleJson() = """
{
"itemId": "suspicious-turnip.345888",
"price": 34.95
}
""".trimIndent()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment