I've been trying to use the Reads[A] in Play as discussed in this post.
Handling JSON requests in Play Framework 2.0 Scala
However, when I tried to do something similar, I ended up getting this error.
object creation impossible, since method reads in trait Reads of type (json: play.api.libs.json.JsValue)models.SomeObject.AnotherObject is not defined
I currently have:
package models
object SomeObject {
case class AnotherObject(val name: String)
implicit object AnotherObjectReads extends Reads[AnotherObject] {
def read(json: JsValue) =
AnotherObject((json \ "name").as[String])
}
}
And I'm using it in the following way:
def callFunc = Action(BodyParsers.parse.json) { request =>
request.body.asOpt[SomeObject.AnotherObject].map {
//Logic
}.getOrElse(BadRequest)
}
Am I doing something wrong in my code?
I think you have it misspelled. The method is called reads not read
http://www.playframework.org/documentation/api/2.0.4/scala/index.html#play.api.libs.json.Reads
Related
No instance of play.api.libs.json.Format is available for akka.actor.typed.ActorRef[org.knoldus.eventSourcing.UserState.Confirmation] in the implicit scope (Hint: if declared in the same file, make sure it's declared before)
[error] implicit val userCommand: Format[AddUserCommand] = Json.format
I am getting this error even though I have made Implicit instance of Json Format for AddUserCommand.
Here is my code:
trait UserCommand extends CommandSerializable
object AddUserCommand{
implicit val format: Format[AddUserCommand] = Json.format[AddUserCommand]
}
final case class AddUserCommand(user:User, reply: ActorRef[Confirmation]) extends UserCommand
Can anyone please help me with this error and how to solve it?
As Gael noted, you need to provide a Format for ActorRef[Confirmation]. The complication around this is that the natural serialization, using the ActorRefResolver requires that an ExtendedActorSystem be present, which means that the usual approaches to defining a Format in a companion object won't quite work.
Note that because of the way Lagom does dependency injection, this approach doesn't really work in Lagom: commands in Lagom basically can't use Play JSON.
import akka.actor.typed.scaladsl.adapter.ClassicActorSystemOps
import play.api.libs.json._
class PlayJsonActorRefFormat(system: ExtendedActorSystem) {
def reads[A] = new Reads[ActorRef[A]] {
def reads(jsv: JsValue): JsResult[ActorRef[A]] =
jsv match {
case JsString(s) => JsSuccess(ActorRefResolver(system.toTyped).resolveActorRef(s))
case _ => JsError(Seq(JsPath() -> Seq(JsonValidationError(Seq("ActorRefs are strings"))))) // hopefully parenthesized that right...
}
}
def writes[A] = new Writes[ActorRef[A]] {
def writes(a: ActorRef[A]): JsValue = JsString(ActorRefResolver(system.toTyped).toSerializationFormat(a))
}
def format[A] = Format[ActorRef[A]](reads, writes)
}
You can then define a format for AddUserCommand as
object AddUserCommand {
def format(arf: PlayJsonActorRefFormat): Format[AddUserCommand] = {
implicit def arfmt[A]: Format[ActorRef[A]] = arf.format
Json.format[AddUserCommand]
}
}
Since you're presumably using JSON to serialize the messages sent around a cluster (otherwise, the ActorRef shouldn't be leaking out like this), you would then construct an instance of the format in your Akka Serializer implementation.
(NB: I've only done this with Circe, not Play JSON, but the basic approach is common)
The error says that it cannot construct a Format for AddUserCommand because there's no Format for ActorRef[Confirmation].
When using Json.format[X], all the members of the case class X must have a Format defined.
In your case, you probably don't want to define a formatter for this case class (serializing an ActorRef doesn't make much sense) but rather build another case class with data only.
Edit: See Levi's answer on how to provide a formatter for ActorRef if you really want to send out there the actor reference.
I'm was reading about cats and I encountered the following code snippet which is about serializing objects to JSON!
It starts with a trait like this:
trait JsonWriter[A] {
def write(value: A): Json
}
After this, there are some instances of our domain object:
final case class Person(name: String, email: String)
object JsonWriterInstances {
implicit val stringWriter: JsonWriter[String] =
new JsonWriter[String] {
def write(value: String): Json =
JsString(value)
}
implicit val personWriter: JsonWriter[Person] =
new JsonWriter[Person] {
def write(value: Person): Json =
JsObject(Map(
"name" -> JsString(value.name),
"email" -> JsString(value.email)
))
}
// etc...
}
So far so good! I can then use this like this:
import JsonWriterInstances._
Json.toJson(Person("Dave", "dave#example.com"))
Later on I come across something called the interface syntax, which uses extension methods to extend existing types with interface methods like below:
object JsonSyntax {
implicit class JsonWriterOps[A](value: A) {
def toJson(implicit w: JsonWriter[A]): Json =
w.write(value)
}
}
This then simplifies the call to serializing a Person as:
import JsonWriterInstances._
import JsonSyntax._
Person("Dave", "dave#example.com").toJson
What I don't understand is that how is the Person boxed into JsonWriterOps such that I can directly call the toJson as though toJson was defined in the Person case class itself. I like this magic, but I fail to understand this one last step about the JsonWriterOps. So what is the idea behind this interface syntax and how does this work? Any help?
This is actually a standard Scala feature, since JsonWriterOps is marked implicit and is in scope, the compiler can apply it at compilation-time when needed.
Hence scalac will do the following transformations:
Person("Dave", "dave#example.com").toJson
new JsonWriterOps(Person("Dave", "dave#example.com")).toJson
new JsonWriterOps[Person](Person("Dave", "dave#example.com")).toJson
Side note:
It's much more efficient to implicit classes as value classes like this:
implicit class JsonWriterOps[A](value: A) extends AnyVal
This makes the compiler also optimize away the new object construction, if possible, compiling the whole implicit conversion + method call to a simple function call.
anyone has good examples on the Scala Controller that calls the Dao methods to get the objects, and convert to json for my reference? I got stuck on the following Controller getProject(id). Please advise.
Thanks
#Singleton
abstract class ProjectController #Inject()(projectDao: ProjectDao) extends BaseController()
{
def index(): Action[AnyContent] = Action {
Ok(com.workday.appsec.midi.views.html.index("Your application is ready."))
}
def getProject(id: Long): Action[AnyContent] = Action { implicit request =>
val proj: Future[Option[Project]] = projectDao.getProjectById($id)
//TODO: GET STUCK HERE!!
//need to convert to json object and return to the response
Json.toJson(proj)
}
}
Here is a sample project that I did. You might find this helpful!
https://github.com/joesan/plant-simulator/blob/master/app/com/inland24/plantsim/controllers/PowerPlantController.scala
The idea is that, you use play json library to serialize de-serialize your case classes to and from json.
You just pass object to Ok
proj.flatMap {
case Some(prj)=>Future.successful(Ok(prj))
case None:
}
I've built a microservice using Scala and Play and now I need to create a new version of the service that returns the same data as the previous version of the service but in a different JSON format. The service currently uses implicit Writes converters to do this. My controller looks something like this, where MyJsonWrites contains the implicit definitions.
class MyController extends Controller with MyJsonWrites {
def myAction(query: String) = Action.async {
getData(query).map {
results =>
Ok(Json.toJson(results))
}
}
}
trait MyJsonWrites {
implicit val writes1: Writes[SomeDataType]
implicit val writes2: Writes[SomeOtherDataType]
...
}
Now I need a new version of myAction where the JSON is formatted differently. The first attempt I made was to make MyController a base class and have subclasses extend it with their own trait that has the implicit values. Something like this.
class MyNewContoller extends MyController with MyNewJsonWrites
This doesn't work though because the implicit values defined on MyNewJsonWrites are not available in the methods of the super class.
It would be ideal if I could just create a new action on the controller that somehow used the converters defined in MyNewJsonWrites. Sure, I could change the trait to an object and import the implicit values in each method but then I'd have to duplicate the method body of myAction so that the implicits are in scope when I call Json.toJson. I don't want to pass them as implicit parameters to a base method because there are too many of them. I guess I could pass a method as a parameter to the base method that actually does the imports and Json.toJson call. Something like this. I just thought maybe there'd be a better way.
def myBaseAction(query: String, toJson: Seq[MyResultType] => JsValue) = Action.async {
getData(query).map {
results =>
Ok(Json.toJson(results))
}
}
def myActionV1(query: String) = {
def toJson(results: Seq[MyResultType]) = {
import MyJsonWritesV2._
Json.toJson(results)
}
myBaseAction(query, toJson)
}
Instead of relying on scala implicit resolution, you can call your writes directly:
def myBaseAction(query: String, writes: Writes[MyResultType]) = Action.async {
getData(query).map { results =>
val seqWrites: Writes[Seq[MyResultType]] = Writes.seq(writes)
Ok(seqWrites.writes(results))
}
}
def myActionV1(query: String) = myBaseAction(query, MyJsonWritesV1)
def myActionV2(query: String) = myBaseAction(query, MyJsonWritesV2)
I'm using elastic4s library to query elasticsearch (ES). Version of elastic4s and ES itself 2.4.0.
Suppose I have a compound object that I put to ES like
case class MyObject(id: Long, vall: KeyVal, vals: Seq[KeyVal])
where KeyVal is
case class KeyVal(id: Long, name: String)
Now I queried ES and got the response which I want to deserialiize back to MyObject:
implicit object MyObjectHitAs extends HitAs[MyObject] {
override def as(hit: RichSearchHit): MyObject = {
MyObject(
hit.field("id").getValue[String]
KeyVal(hit.field("vall.id").getValue[Long], field("vall.name").getValue[String]),
//what should I code here to get the Seq[KeyVal] ???
)
}
}
Please explain how can I deserialize the Array of KeyVal. Thank you.
In the more recent versions of elastic4s, ie 5.0 onwards, you would use the HitReader typeclass. Your example would then look like this.
implicit object MyObjectHitAs extends HitReader[MyObject] {
override def read(hit: Hit): Either[Throwable, MyObject] = {
val obj = MyObject(
hit.sourceField("id").toString.toLong,
KeyVal(hit.sourceField("vall.id").toString.toLong, hit.sourceField("vall.name").toString),
hit.sourceField("vals").asInstanceOf[Seq[AnyRef]].map { entry =>
KeyVal(hit.sourceField("vall.id").toString.toLong, hit.sourceField("vall.name").toString)
}
)
Right(obj)
}
}
Although it is a lot easier to use the built in json mappers than hand craft it.