Created
January 14, 2022 10:32
-
-
Save wplong11/593fc5e29243978e094ed171c697ed75 to your computer and use it in GitHub Desktop.
Mapping string to complex object for @RequestParam
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
| import com.fasterxml.jackson.databind.ObjectMapper | |
| import org.springframework.core.convert.TypeDescriptor | |
| import org.springframework.core.convert.converter.GenericConverter | |
| import org.springframework.stereotype.Component | |
| @Component | |
| class JsonConverter( | |
| private val objectMapper: ObjectMapper | |
| ) : GenericConverter { | |
| override fun getConvertibleTypes() = mutableSetOf( | |
| GenericConverter.ConvertiblePair(String::class.java, Any::class.java) | |
| ) | |
| override fun convert( | |
| value: Any?, | |
| sourceType: TypeDescriptor, | |
| targetType: TypeDescriptor, | |
| ): Any? = value?.let { | |
| when (targetType.type) { | |
| String::class.java -> it | |
| else -> objectMapper.readValue(it as String, targetType.type) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment