0

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 ?

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

It does not work for me. 1) implicit Writes[T] - what if I have case class with property as another case class case class P(val c: Node1)... I need implicits for both of them ?
Of course. You have to decide/code how each type (top level or embedded) should be handled: by default typeclass instances provided by macros or by custom impl.
that what I was talking about. In lift-json there is default formatter. I do not need to code anything.
That's how typeclass system works, you have to decide which instance you want for which type, even if that the default behaviour.
-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.