Skip to content

Instantly share code, notes, and snippets.

@stella6767
Last active August 11, 2022 01:25
Show Gist options
  • Save stella6767/5e0fb8329bc2ac66d846e2db0a2cfd14 to your computer and use it in GitHub Desktop.
Save stella6767/5e0fb8329bc2ac66d846e2db0a2cfd14 to your computer and use it in GitHub Desktop.
convertPojoToUrlEncodedFormData
fun convertPojoToUrlEncodedFormData(obj: Any?): String {
/**
* 간단한 함수 input + output 테스트를 위하므로, ObjectMapper를 의존성 주입시키지 않겠다.(스프링과는 독립적인)
* util function들은 최대한 의존성 없이
*
*/
val map: Map<*, *>? = ObjectMapper().convertValue(obj, Map::class.java)
return map?.keys?.map { key ->
try {
val typeClass: Class<*> = PropertyUtils.getPropertyType(obj, key.toString())
val type = typeClass.simpleName
var value: String? = null
println("type!! $type")
// if (type == "String") {
// value = map[key] as String?
// println("value!! $value")
//
// } else if (typeClass.isPrimitive || typeClass.isKotlinClass() || typeClass.isMemberClass || ) {
// value = java.lang.String.valueOf(map[key])
// println("value? $value")
// }
value = java.lang.String.valueOf(map[key])
println("value? $value")
return@map if (value != null && value.isNotEmpty()) key.toString() + "=" + URLEncoder.encode(
value,
StandardCharsets.UTF_8.toString()
) else null
} catch (e: Exception) {
throw RuntimeException(e.stackTraceToString())
}
null
}
?.filterNotNull()?.joinToString("&") ?: ""
}
@Test
fun convertPojoToUrlEncodedFormDataTest() {
val dto = CategoryRes(
name = "test",
id=1,
type = 2,
scroll = 3,
categoryLevel = CategoryLevel.BIG
)
val data = convertPojoToUrlEncodedFormData(dto)
log.info { """
$data
""".trimIndent() }
}
[main] INFO - id=1&name=test&type=2&scroll=3&categoryLevel=BIG
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment