Goal
- json 텍스트를 파싱해서 Bundle 객체로 만들기
- String, Int, Float, Array 등 타입 모두 처리하기
Implementation
json 파싱
private fun bundleFromJson(json: String): Bundle {
val jsonObject = JSONObject(json)
jsonObject.keys().forEach { key ->
val value = jsonObject.get(key)
...
}
}
jsonObject 에서 얻은 value 타입별로 처리
- Any 로 얻은 값의 simpleName 을 얻어서 처리
val value: Any = jsonObject.get(key)
when (value::class.simpleName) {
"String" -> ...
"Int" -> ...
"Long" -> ...
"Boolean" -> ...
"Float" -> ...
"Double" -> ...
"JSONObject" -> ...
"JSONArray" -> ...
else -> ...
}
bundleFromJson
fun bundleFromJson(json: String): Bundle {
val bundle: Bundle = Bundle()
val jsonObject = JSONObject(json)
jsonObject.keys().forEach { key ->
val value = jsonObject.get(key)
when (value::class.simpleName) {
"String" -> bundle.putString(key, value as String)
"Int" -> bundle.putInt(key, value as Int)
"Long" -> bundle.putLong(key, value as Long)
"Boolean" -> bundle.putBoolean(key, value as Boolean)
"Float" -> bundle.putFloat(key, value as Float)
"Double" -> bundle.putDouble(key, value as Double)
"JSONObject" -> bundle.putBundle(key, bundleFromJson(value.toString()))
"JSONArray" -> bundle.putBundle(key, bundleFromJsonArray(value.toString()))
else -> bundle.putString(key, value::class.simpleName)
}
}
return bundle
}
bundleFromJsonArray
fun bundleFromJsonArray(json: String): Bundle {
val bundle: Bundle = Bundle()
val jsonArray = JSONArray(json)
for (i in 0 until jsonArray.length()) {
bundle.putAll(bundleFromJson(jsonArray[i].toString()))
}
return bundle
}
Source Code
Test
@Test
fun testBundleFromJson() {
val json = """
{
"name": "홍길동",
"age": 20,
"address": [
{
"city": "서울",
"street": "강남구"
}
]
}
""".trimIndent()
val bundle = bundleFromJson(json)
assertEquals(bundle.getString("name"), "홍길동")
assertEquals(bundle.getInt("age"), 20)
assertEquals(bundle.getBundle("address")?.getString("city"), "서울")
assertEquals(bundle.getBundle("address")?.getString("street"), "강남구")
}
이렇게 유용한 정보를 공유해주셔서 감사합니다.