Skip to content

Instantly share code, notes, and snippets.

@jerieljan
Created March 6, 2019 02:45
Show Gist options
  • Save jerieljan/587f8fd5e0aa28c885a028000683523e to your computer and use it in GitHub Desktop.
Save jerieljan/587f8fd5e0aa28c885a028000683523e to your computer and use it in GitHub Desktop.
Jackson + Kotlin makes easy work with JSON.
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
/**
*
*
* Date: 2019-03-05
* Time: 11:03 AM
* @author jerieljan
*/
fun main() {
//Feed sample JSON
val json = "{\n \"product\": {\n \"name\" : \"Test Product\",\n \"description\": \"A test product\",\n \"pricing\": {\n \"TestProduct-1\": {\n \"sku\": \"TestProduct-1\",\n \"price\": \"100\",\n \"currency\": \"USD\",\n \"rate\": \"Hourly\"\n }\n }\n }\n}";
//Use Jackson to load the JSON tree.
val mapper = jacksonObjectMapper()
val parsed = mapper.readTree(json)
//Extract values by bracket notation
val productName = parsed["product"]["name"] ?: "No name"
val productDescription = parsed["product"]["description"] ?: "No description"
//Since it's all in strings (effectively), it's also okay to concatenate values together.
val price = "${parsed["product"]["pricing"].first()["currency"]} ${parsed["product"]["pricing"].first()["price"]}"
//You can even do it the classic way of chaining gets.
val productSku = parsed.get("product")?.get("name")?.get("sku")?.toString() ?: "No SKU"
// Let's try printing.
// Print the product.
println("Printing Basic Values")
println("$productName - $productDescription - $productSku")
println("Price: $price")
println()
//Let's try using a data class / POJO object instead
val testProduct = Product(parsed)
//Print the product.
println("Printing Data Class")
println("Name: ${testProduct.name} Description: ${testProduct.description}")
println()
println("Printing Data Class' built-in toString()")
println(testProduct)
println()
}
data class Product(private val model: JsonNode,
val name: String = model["product"]["name"]?.toString() ?: "No name",
val description: String = model["product"]["description"]?.toString() ?: "No description",
val sku: String = model["product"]["name"]["sku"]?.toString() ?: "No SKU",
val price: String = "${model["product"]["pricing"].first()["currency"]} ${model["product"]["pricing"].first()["price"]}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment