Skip to content

Instantly share code, notes, and snippets.

@anibalbastiass
Created March 23, 2022 15:54
Show Gist options
  • Save anibalbastiass/f694326f0471b6ee21b7adc838a1bdfe to your computer and use it in GitHub Desktop.
Save anibalbastiass/f694326f0471b6ee21b7adc838a1bdfe to your computer and use it in GitHub Desktop.
JSONParserChallenge (Using Gson Library)
import CharterChallenge.Order.OrderItem.SizePrice
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import java.net.URL
class CharterChallenge {
companion object {
private const val GET_ORDER_URL = "https://raw.githubusercontent.com/pgiani/KotlinTask/main/order.json"
@JvmStatic
fun main(args: Array<String>) {
val response = URL(GET_ORDER_URL).readText()
val parser = JSONOrderParser()
val orders = parser.fromJsonToObject(response)
val nonNullableOrders = checkNotNull(orders?.order) {
throw NullPointerException("Orders cannot be null")
}
var total = 0
nonNullableOrders.map { item ->
total += item.size.calculate()
}
println("The price of the order is $total")
}
private fun SizePrice.calculate(): Int {
return when (this) {
SizePrice.SMALL -> SizePrice.SMALL.amount
SizePrice.MEDIUM -> SizePrice.MEDIUM.amount
SizePrice.LARGE -> SizePrice.LARGE.amount
else -> throw IllegalArgumentException("This size is not available")
}
}
}
data class Order(
val order: List<OrderItem> = arrayListOf()
) {
data class OrderItem(
val type: String = "",
@SerializedName("size") val size: SizePrice = SizePrice.DEFAULT,
val toppings: List<String> = arrayListOf(),
val sauce: List<String> = arrayListOf()
) {
enum class SizePrice(internal val amount: Int) {
@SerializedName("small")
SMALL(4),
@SerializedName("medium")
MEDIUM(8),
@SerializedName("large")
LARGE(15),
@SerializedName("default")
DEFAULT(0)
}
}
}
class JSONOrderParser {
fun fromJsonToObject(json: String): Order? = Gson().fromJson(json, Order::class.java)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment