Skip to content

Commit 4aee6a7

Browse files
author
Donovan Levinson
committed
Add test for constructing Writes with case class
Updated syntax in README to support Scala 3
1 parent 51bd5d6 commit 4aee6a7

2 files changed

Lines changed: 37 additions & 3 deletions

File tree

README.md

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -246,19 +246,28 @@ import play.api.libs.functional.syntax._
246246
implicit val locationWrites: Writes[Location] = (
247247
(JsPath \ "lat").write[Double] and
248248
(JsPath \ "long").write[Double]
249-
)(unlift(Location.unapply))
249+
)(location => {
250+
val Location(lat, long) = location
251+
(lat, long)
252+
})
250253

251254
implicit val residentWrites: Writes[Resident] = (
252255
(JsPath \ "name").write[String] and
253256
(JsPath \ "age").write[Int] and
254257
(JsPath \ "role").writeNullable[String]
255-
)(unlift(Resident.unapply))
258+
)(resident => {
259+
val Resident(name, age, role) = resident
260+
(name, age, role)
261+
})
256262

257263
implicit val placeWrites: Writes[Place] = (
258264
(JsPath \ "name").write[String] and
259265
(JsPath \ "location").write[Location] and
260266
(JsPath \ "residents").write[Seq[Resident]]
261-
)(unlift(Place.unapply))
267+
)(place => {
268+
val Place(name, location, residents) = place
269+
(name, location, residents)
270+
})
262271

263272

264273
val place = Place(

play-json/shared/src/test/scala/play/api/libs/json/WritesSharedSpec.scala

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,31 @@ final class WritesSharedSpec extends AnyWordSpec with Matchers {
174174
success[JsValue, Writes](JsString("foo"))
175175
}
176176

177+
"Constructing Writes" should {
178+
"support case class" in {
179+
import play.api.libs.functional.syntax._
180+
181+
implicit val locationReads: Reads[Location] = (
182+
(JsPath \ "lat").read[Double] and
183+
(JsPath \ "long").read[Double]
184+
)(Location.apply _)
185+
186+
implicit val locationWrites: Writes[Location] = (
187+
(JsPath \ "lat").write[Double] and
188+
(JsPath \ "long").write[Double]
189+
)(location => {
190+
val Location(lat, long) = location
191+
(lat, long)
192+
})
193+
194+
val location = Location(1.1, 2.2)
195+
196+
val serialized = Json.stringify(Json.toJson(location))
197+
serialized.mustEqual("""{"lat":1.1,"long":2.2}""")
198+
Json.fromJson[Location](Json.parse(serialized)).mustEqual(JsSuccess(location))
199+
}
200+
}
201+
177202
// ---
178203

179204
case class Location(lat: Double, long: Double)

0 commit comments

Comments
 (0)