ことりんでJsonを扱う変な方法
ちょっとした定義を追加するだけ
素直にmapperで変換した方が楽だと思う。
operator fun <T> JsonNode.getValue(thisRef: Any?, property: KProperty<*>): T = when(property.returnType) { String::class.defaultType -> this[property.name].asText() as T Int::class.defaultType -> this[property.name].asInt() as T else -> null as T } class Test(val json: JsonNode) { val a : String by json val c : Int by json } class KotoJsonTest { @Test fun read() { val mapper = ObjectMapper() val node = mapper.readTree("{\"a\":\"b\",\"c\":1}"); val v = Test(node) assertThat(v.a , Is("b")) assertThat(v.c , Is(1)) } }
valにしか対応してない&型も制限あるけど、こういう使い方もあるんだなぁ〜って思った