0

In my usecase, I have a SourceEvent case class which can take an instance of a generic type as a parameter like this:

case class SourceEvent[T](event: T, hash: Int = 0) extends Command 

When the SourceEvent is being constructed, T is being passed as a Tuple2 like:

SourceEvent[(String,String)](("abc","sample-event"), hash = "sample-event".hashCode) 

When this is received by a Behavior, tuple is being treated as list like this:

message match {
      case m: SourceEvent[(String,String)] =>
context.log.info(s"Message received : ${m}")
Behaviors.same
}

It's printing the below log:

Message received : SourceEvent(List(abc,sample-event),-1486933305)

While trying to access any fields for the tuple like m.event._1, the below exception is being thrown:

[local-test-akka.actor.default-dispatcher-5] ERROR akka.actor.SupervisorStrategy - scala.collection.immutable.$colon$colon cannot be cast to scala.Tuple2

How do we deserialize a Tuple as it is using jackson-json serialization in akka!!

sam.ban
  • 238
  • 3
  • 13

1 Answers1

0

I have not worked much with fasterxml.jackson library, but I think there are some few points that you should consider.

  • First of all is that be aware of type erasure, take a look at this question. If you have noticed, here a SourceEvent[List[String]] is matched as SourceEvent[(String, String)] although you did not want it.
  • Second thing, as I mentioned earlier, I have not worked much with fasterxml.jackson library, but as far as I know, you can define your own custom serializer/deserializers. So you can parse the tuple type manually.
  • Since there is no standard way of representation of tuples in JSON, it is serialized/deserialized to/from arrays. And since tuples are entities that orders of elements matters a lot in them, I suggest you use a safer approach, like modeling your data. For instance, you think the first element of your tuple is the name, and the second one is the country of a person, what if you somehow received ["USA", "John"]? so modeling can help a lot in your case, i.e,. {"name":"John","country":"USA"}
AminMal
  • 3,070
  • 2
  • 6
  • 15
  • Thank you so much.. These are all valid points.. I was thinking if there is a way a tuple is treated as tuple during deserialization using jackson by changing some config. But, looks like that's not possible.. So, will have to change the model of the data the way you mentioned.. Lightbend should mention this limitations in Akka documentation.. – sam.ban Jul 12 '22 at 03:41