Home > Blockchain >  Kotlin Jackson serialization issue
Kotlin Jackson serialization issue

Time:11-23

I'm testing out PubSub message sending which has a bean called PubSubTemplate which allows to send messages towards PubSub and I want to send raw JSON, but I've noticed that other application which consumes PubSub message fails to deserialise it. The issue is when JacksonPubSubMessageConverter converts payload to PubSubMessage it uses ByteString.copyFrom(objectMapper.writeValueAsBytes(payload)) and it double encodes my payload so when reading happens actual json looks like this: \"{ \\\"value\\\": 42 }\"

fun main() {
  val objectMapper = ObjectMapper()
  objectMapper.registerModule(KotlinModule())

  val payload = "{ \"value\": 42 }"

  val payloadEncoded = ByteString.copyFrom(objectMapper.writeValueAsBytes(payload))
  val readValue = objectMapper.readerFor(TestClass::class.java).readValue<TestClass>(payloadEncoded.toByteArray())
  println(readValue)
}

data class TestClass(var value: Int)

How I should create my payload so it would correctly encode it and would be able to deserialize into an object?

CodePudding user response:

ObjectMapper.writeValueAsBytes converts its argument to JSON. Since your payload string is already JSON, you can skip the call to objectMapper.writeValueAsBytes and just call ByteString.copyFrom(payload.toByteArray()).

  • Related