scala - Which JSON library to use when storing case objects? -
i need serialize akka events json. based on "what json library use in scala?" tried several libraries. since serializer should know nothing of concrete events, events consisting of case classes , case objects should serialised using reflection. json4s seems match requirements best.
class json4seventadapter(system: extendedactorsystem) extends eventadapter { implicit val formats = serialization.formats(fulltypehints(list(classof[evt]))) override def tojournal(event: 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 using json4s is, no matter implementation used deserialization of objects produces different instances. since heavily use pattern matching case object breaks our existing code.
so question is: json library used scala , akka persistence when storing case objects?
is there 1 library handles deserialization of case objects via reflection correctly? - or have workaround?
i can't comment on json4s, since i've never used it, know non-issue in play-json. 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 string `myevent`") { case "myevent" => myevent }, writes.pure("myevent"))
in case, serialization bare string, , piggyback on built-in stringreads
assert item should deserializable string, , use collect
narrow down specific string. basic idea provide specific value want deserialization in reads
instance. here, it's singleton case object
. so, whenever deserialize myeventbase
resulting in myevent
, you'll same instance back.
in real world, myeventbase
has other subtypes, , structure writes
instance create form of type tag serialization reads
instance can key off of deserialize proper subtype. like, might serialize json object instead of bare string, , object have type
field identifies subtype. or use play json extensions automatically synthesize reasonable format
sealed trait
.
Comments
Post a Comment