scala - How to write JSON Reads for models without a matching constructor signature? -
i have following json object:
{"values": "123,456,789"}
i'd convert json object instance of class foo
following signature, using json library of play framework:
case class foo(value1: double, value2: double, value3: double)
in documentation json combinators, there examples conversions constructor signature of class matches extracted json values. if had such case, i'd have write following reads function:
import play.api.libs.json._ import play.api.libs.functional.syntax._ implicit val fooreads: reads[foo] = ( (jspath \ "values").read[string] )(foo.apply _)
however, first have split string "123,456,789"
to 3 separate strings, , convert each of them double
values before can create instance of class foo
. how can json combinators? not able find examples that. trying pass in function literal argument not work:
// not work implicit val fooreads: reads[foo] = ( (jspath \ "values").read[string] )((values: string) => { val array(value1, value2, value3) = values.split(",").map(_.todouble) foo(value1, value2, value3) })
the compiler getting confused , thinks passing function (usually implicit) parameter read
method. can around explicitly using reads.map
instead of applicationops.apply
:
implicit val fooreads: reads[foo] = { (jspath \ "values").read[string] map { values => val array(value1, value2, value3) = values.split(",").map(_.todouble) foo(value1, value2, value3) } }
Comments
Post a Comment