Skip to content

Instantly share code, notes, and snippets.

@diewland
Last active May 20, 2020 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diewland/dcac6c36c26793a9544960568e618cc2 to your computer and use it in GitHub Desktop.
Save diewland/dcac6c36c26793a9544960568e618cc2 to your computer and use it in GitHub Desktop.
Parse nested json object to data class
Setting(title=Sample Temp Setting, info=[TimeRange(from=07:00, to=18:00, temp=8), TimeRange(from=18:00, to=00:00, temp=10), TimeRange(from=00:00, to=07:00, temp=12)])
Title: Sample Temp Setting
* 07:00 to 18:00 -> 8 C
* 18:00 to 00:00 -> 10 C
* 00:00 to 07:00 -> 12 C
import com.alibaba.fastjson.JSON
data class Setting (
val title: String,
val info: List<TimeRange>
)
data class TimeRange (
val from: String,
val to: String,
val temp: Int
)
fun main () {
// #1 build from data class
val setting = Setting(
"Sample Temp Setting",
listOf(
TimeRange("07:00", "18:00", 8),
TimeRange("18:00", "00:00", 10),
TimeRange("00:00", "07:00", 12)
)
)
// println(setting)
// #2 create json string
val s = """
{
title: 'Sample Temp Setting',
info: [
{ from: '07:00', to: '18:00', temp: 8, },
{ from: '18:00', to: '00:00', temp: 10, },
{ from: '00:00', to: '07:00', temp: 12, },
]
}
""".trimIndent()
// println(s)
// #3 parse to jsonObject
val o = JSON.parseObject(s)
// println(o)
// #4 parse to data class
val oo = JSON.parseObject(s, Setting::class.javaObjectType)
println(oo)
println("Title: ${oo.title}")
oo.info.forEach {
println(" * ${it.from} to ${it.to} -> ${it.temp} C")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment