Correctly parse JSON to Scala case class

141 views
Skip to first unread message

pedro rijo

unread,
Mar 24, 2016, 7:02:57 PM3/24/16
to play-fr...@googlegroups.com
Hey,

I saw this question on SO:
http://stackoverflow.com/questions/36202938/scala-play-reads-parse-nested-json/36210676

From times to times I find myself in the same position, having some
problems correctly parsing JSON to some Scala case class (often with
Sequences or DateTime).

1) So, how could one answer to the question on SO? The problem is in
parsing the JSON Array of 'Friends' into a Sequence of 'ids' (Longs).

Using a case class for the 'Friend' it would be easy:
https://gist.github.com/pedrorijo91/e8b89b0ae7a1e8d16938

But what about without the case class? How would the Response reader be like?


2) Another typical use case I face is when the JSON contains a long
(let's say json = { "date": 1458860074 }, and I want to map it to a
DateTime using the constructor that receives the long

Note: org.joda.time.DateTime

I would expect something like this to work:

case class Exp(datetime: DateTime)
object Exp {
implicit val reader: Reads[Exp] = (JsPath \ "date").read[Long].map(d
=> new DateTime(d)) (Exp.apply _)
}

But I get a:

type mismatch;
found : org.joda.time.DateTime => plugins.results.traits.config.Exp
required: play.api.libs.json.Reads[?]


3) Is there any good info on this json parse subject? I found
https://www.playframework.com/documentation/2.4.x/ScalaJson but it
doesn't seem very clear to me on how to do such not-so-basic
operations

Thanks,
Pedro

Greg Methvin

unread,
Mar 24, 2016, 10:43:15 PM3/24/16
to play-framework
Hi Pedro,

I think the following will work:

implicit val reader: Reads[Exp] = (JsPath \ "date").read[Long].map(d => Exp(new DateTime(d)))

The apply method is only defined on the CanBuild2 -> CanBuild22 classes in the FunctionalBuilder, which are created implicitly when you use the "and" or "~" syntax helpers. So if you have only one field it doesn't work.



--
You received this message because you are subscribed to the Google Groups "play-framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to play-framewor...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/play-framework/CAPMsMoCuadgECZCWUw-1bzz-ncjeAs07ijfBH-kD5fGeKGQW2Q%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.



--
Greg Methvin
Senior Software Engineer

Reply all
Reply to author
Forward
0 new messages