Skip to content

Instantly share code, notes, and snippets.

@fancellu
Last active May 18, 2020 13:27
Show Gist options
  • Save fancellu/0bea53f1a1dda712e179892785572ce3 to your computer and use it in GitHub Desktop.
Save fancellu/0bea53f1a1dda712e179892785572ce3 to your computer and use it in GitHub Desktop.
PlayJson Example of how to use a strongly typed string via case class, yet not change json
{"name":"dino","myAddress":"some place"}
Person(dino,Address(some place))
Person(John,Address(London))
Address(London)
London
Map(Address(place a) -> KT18 7LY, Address(place b) -> BN26 5HQ)
{"place a":"KT18 7LY","place b":"BN26 5HQ"}
// without keyReads/Writes you would get this on the last line
[["place a","KT18 7LY"],["place b","BN26 5HQ"]]
import play.api.libs.json._
object PlayJsonAnyVal extends App {
final case class Address(path: String) extends AnyVal
object Address {
// this allows Address to be used as a map key, even though it is not a String
implicit val keyReads: KeyReads[Address]= key => JsSuccess(Address(key))
implicit val keyWrites: KeyWrites[Address] = _.path
implicit val addressFormat: Format[Address] = Json.valueFormat[Address]
}
case class Person(name: String, myAddress: Address)
object Person {
implicit val format: Format[Person] = Json.format[Person]
}
val dino = Person("dino", Address("some place"))
val out: JsValue = Json.toJson(dino)
// note, no mention of path in the json or "Address"
println(out)
val dinoin: Person = out.as[Person]
println(dinoin)
val john=Json.parse("""{"name":"John","myAddress":"London"}""").as[Person]
println(john)
println(john.myAddress)
println(john.myAddress.path)
val addressPostCode=Map[Address,String](Address("place a")-> "KT18 7LY", Address("place b")->"BN26 5HQ")
println(addressPostCode)
println(Json.toJson(addressPostCode))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment