Jackson + Kotlin makes easy work with JSON.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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