Last active
October 26, 2016 07:52
-
-
Save abelbryo/33122445806bdfe25d1a1f0867b1bf9d to your computer and use it in GitHub Desktop.
Json formatting with Play Json 2.5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import play.api.libs.functional.syntax._ | |
import play.api.libs.json._ | |
// Example showing different use cases | |
// of json formatting with Play-Json library | |
// case class with parameters | |
final case class DataType[T](value: T) | |
object DataType { | |
implicit def anyDataTypeJsonFmt[T: Format]: Format[DataType[T]] = { | |
((__ \ "value").format[T].inmap(DataType.apply[T], unlift(DataType.unapply[T]))) | |
} | |
} | |
// simple case class | |
final case class Foo(foo: String, bar: Int) | |
object Foo { | |
implicit val fooJsonFmt = Json.format[Foo] | |
} | |
// another with parameter | |
final case class Dimension[T: Numeric](width: DataType[T], height: DataType[T], breadth: DataType[T]) | |
object Dimension { | |
implicit def dimensionJsonFormat[T: Numeric: Format]: Format[Dimension[T]] = { | |
((__ \ "width").format[DataType[T]] ~ | |
(__ \ "height").format[DataType[T]] ~ | |
(__ \ "breadth").format[DataType[T]])(Dimension.apply[T], unlift(Dimension.unapply[T])) | |
} | |
} | |
// another simple | |
final case class Person(name: String, age: Int) | |
object Person { | |
implicit val personJsonFmt: Format[Person] = ( | |
(__ \ "name").format[String] ~ | |
(__ \ "age").format[Int])(Person.apply, unlift(Person.unapply)) | |
} | |
// nested | |
final case class Box(name: String, dim: Dimension[Long]) | |
object Box { | |
implicit val jsonBoxFmt = Json.format[Box] | |
} | |
// running | |
object module extends App { | |
val fooString = DataType("some text") | |
val fooInt = DataType(10) | |
val fooLong = DataType(100L) | |
val fooDouble = DataType(1.0299) | |
val fooBoolean = DataType(false) | |
val fooDataType = DataType(Foo("Ox", 20)) | |
val box = Box("cube", Dimension( | |
DataType[Long](10L), | |
DataType[Long](10L), | |
DataType[Long](10L))) | |
println( | |
Json.prettyPrint( | |
Json.arr( | |
Json.toJson(fooDataType), | |
Json.toJson(fooString), | |
Json.toJson(fooInt), | |
Json.toJson(fooDouble), | |
Json.toJson(box), | |
Json.toJson(fooBoolean)))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment