score:19
it's not necessarily apply
or unapply
functions you need. it's a) a function that constructs whatever the type you need given some parameters, and b) a function that turns an instance of that type into a tuple of values (usually matching the input parameters.)
the apply
and unapply
functions you get for free with a scala case class just happen to do this, so it's convenient to use them. but you can always write your own.
normally you could do this with anonymous functions like so:
import java.sql.timestamp
import play.api.libs.functional.syntax._
import play.api.libs.json._
implicit val timestampformat: format[timestamp] = (
(__ \ "time").format[long]
)((long: long) => new timestamp(long), (ts: timestamp) => (ts.gettime))
however! in this case you fall foul of a limitation with the api that prevents you from writing formats like this, with only one value. this limitation is explained here, as per this answer.
for you, a way that works would be this more complex-looking hack:
import java.sql.timestamp
import play.api.libs.functional.syntax._
import play.api.libs.json._
implicit val rds: reads[timestamp] = (__ \ "time").read[long].map{ long => new timestamp(long) }
implicit val wrs: writes[timestamp] = (__ \ "time").write[long].contramap{ (a: timestamp) => a.gettime }
implicit val fmt: format[timestamp] = format(rds, wrs)
// test it...
val testtime = json.obj("time" -> 123456789)
assert(testtime.as[timestamp] == new timestamp(123456789))
Source: stackoverflow.com
Related Query
- How do I write a JSON Format for an object in the Java library that doesn't have an apply method?
- How to deserialize a JSON object to a Java collection using Jackson in a Spring application that registered the DefaultScalaModule?
- i have wriiten a logout code in welcome.scala.html page but getting errors in that page how can i write the code for it
- How to read and write Anorm object with the new JSON API in Play Framework 2.1-RC2?
- How to define a JSON format for an object with nested generic types?
- How to enrich a Java library class that has static methods (aka enrich an object in Scala)?
- How do I write a query for mongodb using the casbah driver for scala that uses a substring and checks if the field is in a list of supplied values?
- How to write a toCSV method for scala case class that would generate the csv string for the class?
- How write code that creates a Dataset with columns that have the elements of an array column as values and their names being positions?
- How do I write a custom Jackson deserializer to deserialize a json object that contains raw json into a single object?
- How do I make a trait that I can mix into mapped fields to that I don not have to override the same properties for many fields in a database?
- How do I write a generic JSON parser in Play 2.7 for Scala that validates inbound requests?
- What are the relationships between Any, AnyVal, AnyRef, Object and how do they map when used in Java code?
- How the get the classOf for a scala object type
- Noise free JSON format for sealed traits with Play 2.2 library
- How to write a Play JSON writes converter for a case class with a single nullable member
- How to access a Java static method from Scala given a type alias for that class it resides in
- How to write a zipWith method that returns the same type of collection as those passed to it?
- How do I create an explicit companion object for a case class which behaves identically to the replaced compiler provided implicit companion object?
- How to have a Scala standalone application that uses the playframework libraries
- How can I write a function have a polymorphic return type based on the type argument of its type parameter?
- How do I create a generic Scala function that returns an object based on the generic type?
- How to stop gracefully the actor system for an akka-http server that must be deployed.
- Scala: how to write method that returns object typed to implementation type of receiver
- How to get the TypeTag for a class in Java
- How can I provide a compile-time guarantee that my method will return the same object it gets in Scala?
- How to write a Json Reads Combinator for a Map[Int, Long]
- How to dump contents of a Java library to the console?
- How to instantiate a materializer for AkkaStreams when I have a reference to the typed actor system?
- How to make compiler check that 2 method arguments have the same type?
More Query from same tag
- Responsive web pattern on the server side
- Scala : Iterate over type class objects
- Check values of org.apache.spark.sql.Row
- Compress and Serialize a large HashMap in memory
- Copying a case class and changing a list of fields
- For comprehensions Future and Either
- Scala - conditionally sum elements in list using foldLeft
- toDF does not compile though import sqlContext.implicits._ is used
- Multiple parameters lists and default arguments
- Local Maxima of List in Scala
- Scala implicit class must have a primary constructor with exactly one argument in first parameter list
- Is there any trick to use macros in the same file they are defined?
- Apache Spark : When not to use mapPartition and foreachPartition?
- How do I enable multiple watch sources in sbt?
- Extract the repetitive parts of a String by Regex pattern matching in Scala
- Type-safe equals macro?
- How to convert jdbc results to immutable collection
- Not persisting Scala None's instead of persisting as null value
- spark-submit with Mahout error on cluster mode (Scala/java)
- Issues in sbt - scala project dockerisation
- how to do non blocking wait on a future for 10 seconds?
- Sharing the business layer between applications in Scala
- Use a scala companion object for spring controller instead of implementing at the service layer?
- Scala Option[(A, B)] pattern matching
- Sum of arrays elementwise using Spark Scala
- Why is this class not found?
- null.==(obj) does not throw null pointer exception in scala
- Get object for element that has failed XSD validation
- I have an array of array and passing it to a function in scala but getting errors
- Pass class as argument to check local variable