Skip to content

Instantly share code, notes, and snippets.

@wplong11
Created January 14, 2022 10:32
Show Gist options
  • Select an option

  • Save wplong11/593fc5e29243978e094ed171c697ed75 to your computer and use it in GitHub Desktop.

Select an option

Save wplong11/593fc5e29243978e094ed171c697ed75 to your computer and use it in GitHub Desktop.
Mapping string to complex object for @RequestParam
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