英文:
Kotlin sealed class Jackson different place in memory
问题
最近,我开始使用Kotlin,并在使用Spring进行JSON映射测试时遇到了一些奇怪的行为。
我创建了类似于以下的东西:
@SpringBootTest(classes = [TestApplication::class])
class JacksonIntegrationTest {
@Autowired
lateinit var objectMapper: ObjectMapper
var objectMapperTest = TestObjectMapper()
@Test
fun `should serialize and deserialize object`() {
//given
val value = SealedObject
//when
val jsonTest = objectMapperTest.writeValueAsString(value)
val resultTest: SealedObject = objectMapperTest.readValue(jsonTest)
val json = objectMapper.writeValueAsString(value)
val result: SealedObject = objectMapper.readValue(json)
//then`
assertThat(result).isSameAs(value)
assertThat(resultTest).isSameAs(value) <---------- 失败
}
internal sealed class Sealed
internal object SealedObject: Sealed()
}
value = JacksonIntegrationTest$SealedObject@6727e0cd <-------------
result (SPRING) = JacksonIntegrationTest$SealedObject@6727e0cd <----- 相同的内存位置
resultTest (OWN) = JacksonIntegrationTest$SealedObject@3c8e3f98
正如您所看到的,Spring的ObjectMapper返回了与原始值在内存中相同引用的值。
但是自己创建的ObjectMapper返回了位于不同内存位置的对象。为什么?
所有的结果应该具有相同的内存位置。
英文:
Recently, I have started with Kotlin and I encountered some strange behavior while testing JSON mapping with Spring.
I created something like this:
@SpringBootTest(classes = [TestApplication::class])
class JacksonIntegrationTest {
@Autowired
lateinit var objectMapper: ObjectMapper
var objectMapperTest = TestObjectMapper()
@Test
fun `should serialize and deserialize object`() {
//given
val value = SealedObject
//when
val jsonTest = objectMapperTest.writeValueAsString(value)
val resultTest: SealedObject = objectMapperTest.readValue(jsonTest)
val json = objectMapper.writeValueAsString(value)
val result: SealedObject = objectMapper.readValue(json)
//then`
assertThat(result).isSameAs(value)
assertThat(resultTest).isSameAs(value) <---------- FAILED
}
internal sealed class Sealed
internal object SealedObject: Sealed()
}
value = JacksonIntegrationTest$SealedObject@6727e0cd <-------------\
result (SPRING) = JacksonIntegrationTest$SealedObject@6727e0cd <----- SAME MEMORY PLACE
resultTest (OWN) = JacksonIntegrationTest$SealedObject@3c8e3f98
As you can see, spring objectmapper returned value with same reference at memory as origin value.
But own created ObjectMapper returned object at different place at memory. Why?
All results should've same memory place
答案1
得分: 2
好的,我找到了一个解决方案。
.registerModule(
kotlinModule(
initializer = {
configure(KotlinFeature.SingletonSupport, true)
},
),
)
英文:
Okay, I've found a solution.
.registerModule(
kotlinModule(
initializer = {
configure(KotlinFeature.SingletonSupport, true)
},
),
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论