diff --git a/README.md b/README.md index 914fd2b4..4c00f271 100644 --- a/README.md +++ b/README.md @@ -246,19 +246,28 @@ import play.api.libs.functional.syntax._ implicit val locationWrites: Writes[Location] = ( (JsPath \ "lat").write[Double] and (JsPath \ "long").write[Double] -)(unlift(Location.unapply)) +)(location => { + val Location(lat, long) = location + (lat, long) +}) implicit val residentWrites: Writes[Resident] = ( (JsPath \ "name").write[String] and (JsPath \ "age").write[Int] and (JsPath \ "role").writeNullable[String] -)(unlift(Resident.unapply)) +)(resident => { + val Resident(name, age, role) = resident + (name, age, role) +}) implicit val placeWrites: Writes[Place] = ( (JsPath \ "name").write[String] and (JsPath \ "location").write[Location] and (JsPath \ "residents").write[Seq[Resident]] -)(unlift(Place.unapply)) +)(place => { + val Place(name, location, residents) = place + (name, location, residents) +}) val place = Place( diff --git a/play-json/shared/src/test/scala/play/api/libs/json/WritesSharedSpec.scala b/play-json/shared/src/test/scala/play/api/libs/json/WritesSharedSpec.scala index 728b0fef..e9b057ef 100644 --- a/play-json/shared/src/test/scala/play/api/libs/json/WritesSharedSpec.scala +++ b/play-json/shared/src/test/scala/play/api/libs/json/WritesSharedSpec.scala @@ -174,6 +174,31 @@ final class WritesSharedSpec extends AnyWordSpec with Matchers { success[JsValue, Writes](JsString("foo")) } + "Constructing Writes" should { + "support case class" in { + import play.api.libs.functional.syntax._ + + implicit val locationReads: Reads[Location] = ( + (JsPath \ "lat").read[Double] and + (JsPath \ "long").read[Double] + )(Location.apply _) + + implicit val locationWrites: Writes[Location] = ( + (JsPath \ "lat").write[Double] and + (JsPath \ "long").write[Double] + )(location => { + val Location(lat, long) = location + (lat, long) + }) + + val location = Location(1.1, 2.2) + + val serialized = Json.stringify(Json.toJson(location)) + serialized.mustEqual("""{"lat":1.1,"long":2.2}""") + Json.fromJson[Location](Json.parse(serialized)).mustEqual(JsSuccess(location)) + } + } + // --- case class Location(lat: Double, long: Double)