What JSON library to use when storing object objects?

I need to serialize akka events for json. Based on “ What is the JSON library to use in Scala? ” I tried several libraries. Since my serializer does not need to know anything about all my specific events, events consisting of case and case classes must be serialized using reflection. json4s seems to fit my requirements.

class Json4sEventAdapter(system: ExtendedActorSystem) extends EventAdapter {
  implicit val formats = Serialization.formats(FullTypeHints(List(classOf[Evt])))
  override def toJournal(event: Any): Any = event match {
case e: AnyRef =>
  write(e).getBytes(Charsets.UTF_8)}

override def fromJournal(event: Any, manifest: String): EventSeq = event match {
case e: Array[Byte] => {
      EventSeq.single(read[Evt](new String(e.map(_.toChar))))}}

The problem with using json4s is that no matter which implementation is used, Deserialization of objects creates different instances . Since we heavily use pattern matching for the case object, this breaks up all of our existing code.

So my question is: what kind of JSON library can be used while saving scala and akka when storing object objects?

Is there even one library that correctly handles the deserialization of object objects? - or does anyone have a good workaround?

+4
source share
2 answers

I can not comment on Json4s since I have never used it, but I know that this is not a problem in play-json . You would do something like:

import play.api.libs.json._

sealed trait MyEventBase
case object MyEvent extends MyEventBase

implicit val myEventBaseFormat: Format[MyEventBase] = Format(Reads.StringReads.collect(ValidationError("must be the string `MyEvent`") {
  case "MyEvent" => MyEvent
}, Writes.pure("MyEvent"))

, StringReads , , collect, . , , Reads. singleton case object. , , deserialize MyEventBase, MyEvent, .

MyEventBase, , , Writes - , Reads , , JSON , type, . - JSON Extensions, Format sealed trait.

0

Stamina. , akka-persistence.

json ( -json ), , , -, .

0

Source: https://habr.com/ru/post/1599874/


All Articles