scala - Is it possible to override the way play.api.libs.json write options? -


i work play! scala 2.4 , have several simple case class one:

case class a(a: option[string])  

i override way json.tojson(a) works when option empty.

here have done:

implicit val awrites: writes[a] = json.writes[a]  implicit def ow[t](implicit w: writes[t]): writes[option[t]] = writes {   case none => jsstring("[]")   case some(t) => json.tojson(t) }  json.tojson(a(a = none)) mustbe json.parse("""{"a":"[]"}""") 

but still parses class usual (i.e. {} instead of {"a":"[]"} like).
can in order make test pass?

this isn't possible using json.writes macro, because written specially handle option use readnullable[b]. means need need use combinators define writes[a]. unfortunately, defining writes object 1 field little more cumbersome 1 has more.

implicit val awrites: writes[a] = writes(a => json.obj("a" -> a.a))  scala> json.tojson(a(none)) res8: play.api.libs.json.jsvalue = {"a":"[]"} 

example multiple fields:

import play.api.libs.functional.syntax._ import play.api.libs.json._  case class a(a: option[string], b: int)  implicit val awrites: writes[a] = (     (__ \ "a").write[option[string]] ,     (__ \ "b").write[int] )(unlift(a.unapply))  scala> json.tojson(a(none, 10)) res0: play.api.libs.json.jsvalue = {"a":"[]","b":10} 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -