TroubleShooting

Unrecognized field "address" (class me.kotlin.sample.sample.SimpleData), not marked as ignorable (2 known properties: "first_name", "last_name"]) at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: me.kotlin.sample.sample.SimpleData["ad..

에디개발자 2021. 5. 12. 07:00
반응형

ObjectMapper를 사용하던 중 에러 발생!

나를 닮았다고 한다...

증상

에러 메시지

Unrecognized field "address" (class me.kotlin.sample.sample.SimpleData), not marked as ignorable (2 known properties: "first_name", "last_name"]) at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: me.kotlin.sample.sample.SimpleData["address"])

 

OtherData 데이터 객체를 SimpleData 데이터 객체로 바꾸는 중 에러 발생 

class OtherData(
    val lastName: String? = null,
    val firstName: String? = null,
    val address: String? = null,
    val age: Int? = null,
)
class SimpleData(
    val lastName: String? = null,
    val firstName: String? = null,
)

 

사용하는 ObjectMapper Util 클래스

class MapperUtils {

    companion object {
        private val objectMapper: ObjectMapper = ObjectMapper()
        
        fun getMapper(): ObjectMapper = this.objectMapper

    }
}

Test Code

@Test
fun `Mapper Convert Test`() {
    // Given
    val otherData = OtherData(
        lastName = "lim",
        firstName = "yongtae",
        address = "강남",
        age = 33
    )


    // When
    val simpleData = MapperUtils.getMapper().convertValue(otherData, SimpleData::class.java)

    // Then
    assertThat(simpleData.lastName).isEqualTo("lim")
}

 

 

원인

Convert하여 데이터를 적용하려는 객체에 address, age 필드가 없어서 에러 발생

 

해결

ObjectMapper에 설정값 추가

class MapperUtils {

    companion object {
        private val objectMapper: ObjectMapper = ObjectMapper()
        
        fun getMapper(): ObjectMapper = getObjectMapper(this.objectMapper)


        private fun getObjectMapper(objectMapper: ObjectMapper) =
            objectMapper
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

    }
}
반응형