Skip to content

Instantly share code, notes, and snippets.

@tyrantkhan
Last active June 6, 2020 00:30
Show Gist options
  • Save tyrantkhan/e31ef545593e0998140133115b1b4c6e to your computer and use it in GitHub Desktop.
Save tyrantkhan/e31ef545593e0998140133115b1b4c6e to your computer and use it in GitHub Desktop.
Jackson <-> Kotlin with a custom Introspector
buildscript {
ext.kotlin_version = '1.3.10'
ext.jacksonVersion = '2.9.0'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: 'kotlin'
apply plugin: 'application'
mainClassName = 'demo.HelloWorldKt'
defaultTasks 'run'
repositories {
mavenCentral()
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
testCompile 'junit:junit:4.11'
testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
compile "com.fasterxml.jackson.module:jackson-module-kotlin:$jacksonVersion"
}
jar {
manifest { attributes 'Main-Class': 'demo.HelloWorldKt' }
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
}
task wrapper(type: Wrapper) {
gradleVersion = "4.10.2"
}
package demo
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.databind.PropertyName
import com.fasterxml.jackson.databind.introspect.Annotated
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector
class CustomAnotationInspector() :
JacksonAnnotationIntrospector() {
override fun findNameForSerialization(annotation: Annotated): PropertyName {
var pn = super.findNameForSerialization(annotation)
if (annotation.hasAnnotation(JsonProperty::class.java)) {
return pn
}
// if not annotated, value may be set dynamically
pn = if(annotation.name == "average") {
PropertyName("f_average")
} else {
PropertyName(annotation.name)
}
return pn
}
}
package demo
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
fun getGreeting(): String {
val mapper = jacksonObjectMapper()
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.setAnnotationIntrospector(CustomAnotationInspector())
val helloWorldJson = """{"salutation": "Hello","name": "World", "f_average": "92"}"""
val greeting = mapper.readValue(helloWorldJson, Greeting::class.java)
return greeting.salutation + " " + greeting.name + "!"
}
fun main(args: Array<String>) {
println(getGreeting())
}
data class Greeting(val salutation: String, val name: String, val foo: String?, val average: Int)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment