Skip to content

Instantly share code, notes, and snippets.

@Blquinn
Created August 25, 2019 22:17
Show Gist options
  • Save Blquinn/8b848cd7163fb77f7fa3450cb49e8dfa to your computer and use it in GitHub Desktop.
Save Blquinn/8b848cd7163fb77f7fa3450cb49e8dfa to your computer and use it in GitHub Desktop.
Example of deserializing list of dynamic json with jackson.
data class Envelope(
val type: String,
val payload: JsonNode
)
data class Thing1(
val property: String
)
data class Thing2(
val property: String
)
val objectMapper = ObjectMapper()
objectMapper.registerKotlinModule()
val json = """[{"type": "thing1", "payload": {"property": "foo"}},{"type": "thing2", "payload": {"property": "foo"}}]"""
val objs: List<Envelope> = objectMapper.readValue(json)
val deserialized = mutableListOf<Any>()
for (obj in objs) {
val javaType = when (obj.type) {
"thing1" -> Thing1::class.java
"thing2" -> Thing2::class.java
else -> null
}
if (javaType != null) deserialized.add(objectMapper.treeToValue(obj.payload, javaType))
}
for (obj in deserialized) {
when (obj) {
is Thing1 -> println("Is thing1 $obj")
is Thing2 -> println("Is thing1 $obj")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment