Simple Scala JSON library for non-recursive case classes -
i have case classes contain strings or collections of strings , want convert them json objects corresponding field names plus additional field denote type.
sealed trait item case class productx(a: string, b: string) extends item case class producty(a: string, b: string) extends item case class collx(els: list[string]) extends item case class colly(els: list[string]) extends item
most libs have special support case classes there never seems way use in conjunction additional type field disambiguate isomorphic cases, , i'd have fall more low-level descriptions.
so far i've tried spray-json , argonaut , wind way more boilerplate simple usage scenario justify:
// spray-json implicit object collxjsonformat extends rootjsonformat[collx] { def write(ss: collx) = jsobject( "type" -> jsstring("collx"), "els" -> jsarray(ss.els.map(jsstring(_)): _*) ) def read(value: jsvalue) = { value.asjsobject.getfields("type", "els") match { case seq(jsstring("collx"), jsarray(els)) => collx(els.tolist.map({ case jsstring(s) => s case _ => throw new deserializationexception("jsstring expected") })) case _ => throw new deserializationexception("collx expected") } } }
for argonaut couldn't figure out how match type field since decoderesult
has no filter method:
// argonaut implicit def collxcodec: codecjson[collx] = codecjson( (px: collx) => ("type" := "collx") ->: ("els" := px.els) ->: jemptyobject, c => { t <- (c --\ "type").as[string] els <- (c --\ "els").as[list[string]] } yield collx(els))
is there lib can handle better or there feature in 1 of these libs i've overlooked reduce boilerplate?
i use: net.liftweb results.
you can create json way. example if have:
case class abjsontemplate(a: string, b: string)
you can create json this:
net.liftweb.json.serialization.write(abjsontemplate("a", "b"))
in sbt:
librarydependencies += "net.liftweb" %% "lift-json" % "3.0-m1"
i hope can help.
Comments
Post a Comment