Created
March 31, 2020 17:55
-
-
Save noob9527/f3ba50c8ca0cfe6e067cbeb1410d25b0 to your computer and use it in GitHub Desktop.
Fix Jackson Kotlin Boolean naming strategy (before: isFoo => foo, after: isFoo => isFoo)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object JacksonUtil { | |
val objectMapper = ObjectOMapper() | |
.registerKotlinModule() | |
.setPropertyNamingStrategy(FixBooleanPropertyNamingStrategy)!! | |
object FixBooleanPropertyNamingStrategy : PropertyNamingStrategy() { | |
private val logger = LoggerFactory.getLogger(FixBooleanPropertyNamingStrategy::class.java) | |
override fun nameForGetterMethod(config: MapperConfig<*>?, method: AnnotatedMethod, defaultName: String?): String { | |
if (method.hasReturnType() | |
&& (method.rawReturnType == Boolean::class || method.rawReturnType == Boolean::class.javaPrimitiveType) | |
&& method.name.startsWith("is") | |
) { | |
return method.name | |
} | |
return super.nameForGetterMethod(config, method, defaultName) | |
} | |
/** | |
* if | |
* 1. method name starts with set, e.g. setFoo | |
* 2. return type is Boolean or boolean(jvm primitive type) | |
* 3. the declaring class contains a method named isFoo | |
* we return isFoo as the property name in json | |
* | |
* refer to https://stackoverflow.com/a/58999529 | |
*/ | |
override fun nameForSetterMethod(config: MapperConfig<*>?, method: AnnotatedMethod, defaultName: String?): String { | |
logger.trace { "${method.name} $defaultName " + super.nameForSetterMethod(config, method, defaultName) } | |
if (method.parameterCount == 1 | |
&& (method.getRawParameterType(0) == Boolean::class || method.getRawParameterType(0) == Boolean::class.javaPrimitiveType) | |
&& method.name.startsWith("set") | |
) { | |
try { | |
val potential_name = "is${method.name.substring(3)}" | |
method.declaringClass.getMethod(potential_name) | |
logger.trace { potential_name } | |
return potential_name | |
} catch (e: NoSuchMethodException) { | |
logger.trace { e } | |
} | |
} | |
return super.nameForSetterMethod(config, method, defaultName) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment