vvg
vvg

Reputation: 6385

Build JSON from object PlayFramework

To build JSON from scala case class using Play ScalaJson (https://www.playframework.com/documentation/2.4.x/ScalaJson) I have to either manual construct JsObject or implement implicit Writes (that actually means also manual work).

While using lift-web json lib I can define implicit f Formats = net.liftweb.json.DefaultFormats and all transformation will be done in background.

Is any way how scala case classes can be easily transformed in json with play framework json lib ?

Upvotes: 0

Views: 155

Answers (2)

Luong Ba Linh
Luong Ba Linh

Reputation: 802

A simple solution is using Play Json containing helper functions to handle JsValues, and define an implicit format in the companion object of the model. This format will be used implicitly in both serialization and deserialization. Below is an example.

import play.api.libs.json.Json

case class User(name: String, age: Int)

object {
  implicit val format = Json.format[User]
}

For a more comprehensive example, please take a look at this repository:https://github.com/luongbalinh/play-mongo/blob/master/app/models/User.scala

Upvotes: -1

cchantep
cchantep

Reputation: 9168

You can use the macro to define the instances or OWrites[T], Reads[T] or OFormat[T] for any case class T.

implicit val writes: Writes[T] = play.api.libs.json.Json.writes[T]
// Same for Reads or OFormat

Since the OFormat or the OWrites is defined (available as implicit), the .toJson can be used.

val jsValue: JsValue = Json.toJson(instanceOfT)

To keep the object specificity, that's to say having the JsValue typed as JsObject, the .writes can be called directly.

val jsObj: JsObject = implicitly[OWrites[T]].writes(instanceOfT)
// works even if a OFormat is defined, as 'compatible'

Since the OFormat or the Reads is defined, the .fromJson can be used.

val t: JsResult[T] = Json.fromJson[T](jsValue)

Upvotes: 2

Related Questions