implicit json read and writes for lists - json

I am following the following example https://github.com/leon/play-salat/tree/master/sample . In my data model I have lists and I tried to adopt the model to that.
I get the following compilation errors:
[error] /home/malte/workspace/bdt/app/models/Ballot.scala:26: No Json deserializer found for type List[models.Position]. Try to implement an implicit Writes or Format for this type.
[error] "positions" -> b.positions,
[error] ^
[error] /home/malte/workspace/bdt/app/models/Ballot.scala:33: No Json deserializer found for type List[models.Position]. Try to implement an implicit Reads or Format for this type.
[error] (__ \ 'values).read[List[Position]]).map { l => l.getOrElse(Nil) } ~
For the type "Position" I have implicit reads and writes, but how to make it for List[Position] ? My implicit write and read:
implicit val ballotJsonWrite = new Writes[Ballot] {
def writes(b: Ballot): JsValue = {
Json.obj(
"positions" -> b.positions,
"title" -> b.title)
}
}
implicit val ballotJsonRead = (
(__ \ 'positions).readNullable(
(__ \ 'values).read[List[Position]]).map { l => l.getOrElse(Nil) } ~
(__ \ 'title).read[String])(Ballot.apply _)
For the read I followed Create implicit json read for List collection which might be missing from input json , but I get the above mentioned error.

actually now I found out that in the latest versions of salat. Json is automatically used to move between models and json objects. I removed the whole part and no it runs smoothly.
https://github.com/novus/salat/wiki/JSON

Related

No Json serializer as JsObject found for type reactivemongo.play.json.JSONSerializationPack.type

I am using play framework 2.5.3 with reactive mongoDB.
import javax.inject._
import model._
import play.api.Logger
import play.api.libs.json._
import play.api.mvc._
import play.modules.reactivemongo._
import reactivemongo.api.ReadPreference
import reactivemongo.play.json._
import reactivemongo.play.json.collection._
import scala.concurrent.{ExecutionContext, Future}
class InsertController #Inject()(val reactiveMongoApi: ReactiveMongoApi)(implicit exec: ExecutionContext) extends Controller with MongoController with ReactiveMongoComponents {
def dataFuture: Future[JSONCollection] = database.map(_.collection[JSONCollection]("data"))
def createFromJson = Action.async(parse.json) { request =>
Json.fromJson[jsonWrapper](request.body) match {
case JsSuccess(data, _) =>
for {
data <- dataFuture
lastError <- data.insert(data)
} yield {
Logger.debug(s"Successfully inserted with LastError: $lastError")
Ok("Inserted into db")
}
case JsError(errors) =>
Future.successful(BadRequest("Something went wrong"))
}
}
Here is my controller and when compiling i get the following exception:
[info] Compiling 6 Scala sources and 1 Java source to /home/***/target/scala-2.11/classes...
[error] /home/***/app/controllers/InsertController.scala:38: No Json serializer as JsObject found for type reactivemongo.play.json.JSONSerializationPack.type. Try to implement an implicit OWrites or OFormat for this type.
[error] lastError <- data.insert(data.pack)
[error] ^
[error] one error found
[error] (compile:compile) Compilation failed
[info] Compiling 6 Scala sources and 1 Java source to /home/***/target/scala-2.11/classes...
[error] /home/***/app/controllers/InsertController.scala:38: No Json serializer as JsObject found for type reactivemongo.play.json.JSONSerializationPack.type. Try to implement an implicit OWrites or OFormat for this type.
[error] lastError <- data.insert(data.pack)
[error] ^
[error] one error found
[error] (compile:compile) Compilation failed
[error] application -
! #705di1397 - Internal server error, for (GET) [/] ->
play.sbt.PlayExceptions$CompilationException: Compilation error[No Json serializer as JsObject found for type reactivemongo.play.json.JSONSerializationPack.type. Try to implement an implicit OWrites or OFormat for this type.]
at play.sbt.PlayExceptions$CompilationException$.apply(PlayExceptions.scala:27)
at play.sbt.PlayExceptions$CompilationException$.apply(PlayExceptions.scala:27)
at scala.Option.map(Option.scala:145)
at play.sbt.run.PlayReload$$anonfun$taskFailureHandler$1.apply(PlayReload.scala:49)
at play.sbt.run.PlayReload$$anonfun$taskFailureHandler$1.apply(PlayReload.scala:44)
at scala.Option.map(Option.scala:145)
at play.sbt.run.PlayReload$.taskFailureHandler(PlayReload.scala:44)
at play.sbt.run.PlayReload$.compileFailure(PlayReload.scala:40)
at play.sbt.run.PlayReload$$anonfun$compile$1.apply(PlayReload.scala:17)
at play.sbt.run.PlayReload$$anonfun$compile$1.apply(PlayReload.scala:17)
It recommends writing a Owrites or OFormat for JSONCollection which is part of the reactivemongo.play.json._ package and should already have these defined to my understanding.
Here is my jsonWrapper class:
case class jsonWrapper(tables : tables, userId : String)
object jsonWrapper{
implicit val jsonRead: Reads[jsonWrapper] = (
(JsPath \ "tables").read[tables] and
(JsPath \ "userID").read[String]
)(jsonWrapper.apply _)
implicit val jsonWrites: Writes[jsonWrapper] = (
(JsPath \ "tables").write[tables] and
(JsPath \ "userID").write[String]
)(json => (json.tables, json.userId))
implicit val jsonWrapperFormat : Format[jsonWrapper] = Json.format[jsonWrapper]
}
The tables class also has implictly defined format, Reads and writes.
I orignally used this example to get started:
https://github.com/jonasanso/play-reactive-mongo-db#master, which works but when i try to adapt it to my needs (i.e. with my jsonWrapper class) i get this error and do not understand why it is not working.
Many Thanks,
Peter M.
I Found my error.
def createFromJson = Action.async(parse.json) { request =>
Json.fromJson[jsonWrapper](request.body) match {
case JsSuccess(data, _) =>
for {
data <- dataFuture
lastError <- data.insert(data)
} yield {
Logger.debug(s"Successfully inserted with LastError: $lastError")
Ok("Inserted into db")
}
case JsError(errors) =>
Future.successful(BadRequest("Something went wrong"))
}
My case entry initiates an object named "data" which i follow up by overriding with my dataFuture object. Thus, causing the error. I simply had to change the variable names...
I fell kind of silly.

JSON implicit Reads/Writes in Playframerowk with one element not working

Say I have to classes that I will be using it for read and write JSON
case class OrganizationData(var kind: Option[String],var id: Option[String],var organizationReference: OrganizationReferenceData,var objectHash: Option[String],var friendlyName: Option[String])
case class OrganizationReferenceData(var organizationId:String)
The following are the read and write
implicit val organizationWrites = (
(__ \ "kind").writeNullable[String] and
(__ \ "id").writeNullable[String] and
(__ \ "organizationReference").write[OrganizationReferenceData] and
(__ \ "objectHash").writeNullable[String] and
(__ \ "friendlyName").writeNullable[String]
) ( unlift( OrganizationData.unapply ) )
implicit val OrganizationReferenceDataWrites:Writes[OrganizationReferenceData] = (
(__ \ "organizationId").write[String]
) ( unlift( OrganizationReferenceData.unapply ) )
when I try to compile this I am getting the following error.
Error:(54, 34) overloaded method value write with alternatives:
(t: String)(implicit w: play.api.libs.json.Writes[String])play.api.libs.json.OWrites[play.api.libs.json.JsValue] <and>
(implicit w: play.api.libs.json.Writes[String])play.api.libs.json.OWrites[String]
cannot be applied to (config.core.OrganizationReferenceData => String)
(__ \ "organizationId").write[String]
^
Am I missing some thing here? One weird thing that I have seen is if I add another field in "OrganizationReferenceDataWrites" class and have the write element it compiles. SO if we cannot have a single element that what is the best practice to do it?
I'm not sure why you are getting that message, but an alternative way to do it may be:
implicit val OrganizationReferenceDataWrites = new Writes[OrganizationReferenceData] {
def writes(organizationReferenceData: OrganizationReferenceData) = Json.obj(
"organizationId" -> organizationReferenceData.organizationId)
}
Caveat: I don't know my combinators well enough to know if this is exactly equivalent.
BTW Are you using mutable (var) variables for a reason?

Play Scala JSON: combine properties

I have the following case class:
case class User(name: String).
I am trying to implement a JSON Reads converter for it, so I can do the following:
val user = userJson.validate[User]
… but the incoming JSON has slightly different structure:
{ "firstName": "Bob", "lastName": "Dylan" }.
How can I implement my JSON Reads converter to combine the JSON fields firstName and lastName into a name property on my class?
This should do the trick:
implicit val userReads: Reads[User] =
for {
first <- (__ \ "firstName").read[String]
last <- (__ \ "lastName").read[String]
} yield User(s"$first $last")
EDIT
Without using a for comprehension
implicit val userReads =
{
(__ \ "firstName").read[String] and
(__ \ "lastName"
}.read[String] ).tupled.map(t => User(s"${t._1} ${t._2}"))
Bringing userReads in scope where you want to use it will let you parse the JSON you provided.
Reads is essentially a function from JsValue to JsResult, meaning userReads represents a function from JsValue -> JsResult. Within the function, it first inspects the provided JSON & tries to read out a property named "firstName" from the current JSON path (__ is shorthand for this). \ indicates that the field its looking for is one level beneath the root, and read[String] means the value associated with the "firstName" key should be read as a string. Same follows for "lastName".
Edit
In the version without the for comprehension, it first creates an intermediary object FunctionalBuilder[Reads]#CanBuild[String, String], which is a complicated way of saying it reads two distinct strings from the Json. Next it converts that complex object into a Reads[(String, String)] by way of tupled. Finally it maps the pair of strings into a User.
Were you to try validating some JSON without "firstName" & "lastName", this will fail with a validation error for a missing path.

Play Framework 2 JSON Reads, deserialization of one variable

I'm using Play Framework 2.4 and I'm trying to do a basic JSON deserialization with Reads but I get an error. Here is the code:
case class Config(action: String)
and somewhere,
implicit val configReads: Reads[Config] = (
(__ \ "action").read[String]
)(Config.apply _)
I think the configReads is correctly formed but I get an IDE error on the "read" method call (symbol not defined), when I compile the code I get the following error:
Error:(30, 27) overloaded method value read with alternatives:
(t: String)play.api.libs.json.Reads[String] <and>
(implicit r: play.api.libs.json.Reads[String])play.api.libs.json.Reads[String]
cannot be applied to (String => wings.common.json.Config)
(__ \ "action").read[String]
^
but, if instead of trying to deserialize ONE argument I declare a class with TWO arguments in the constructor and I write the code to deserialize it, it works.
Does anybody know how to solve this?
Edit:
Digging in the depth of Google I found this for Play 2.1.x but I'm using the Json library for Play 2.4.1 so this problem should not be happening.
You can do like this:
implicit val configReads: Reads[Config] = (
(__ \ "action").read[String]
) map Config.apply

Json Scala object serialization in Play2.2.1 framework

So, I've just recently started learning Scala. Sorry for my incompetence in advance.
I tried to look up my answer on stackoverflow. I was able to find several related topics, but I didn't spot my problem.
I'm trying to send a json response based on a Scala object. I have an Action and I'm doing the following:
def oneCredential = Action {
val cred = Credential("John", "Temp", "5437437")
Ok(Json.toJson(cred))
}
I've created a case class and appropriate implicit Writes[T] for it
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.libs.json.util._
case class Credential(name: String, account: String, password: String)
object Credential{
implicit val credentialWrites = (
(__ \ "name").write[String] and
(__ \ "account").write[String] and
(__ \ "password").write[String]
)(Credential)
}
When I'm trying to run this, I've the following error: "Overloaded method value [apply] cannot be applied to (models.Credential.type)". Also, I tried this
implicit val credentialWrites = (
(__ \ "name").write[String] and
(__ \ "account").write[String] and
(__ \ "password").write[String]
)(Credential.apply _)
Fail. The error: could not find implicit value for parameter fu: play.api.libs.functional.Functor[play.api.libs.json.OWrites]
Then this:
implicit val credentialWrites = (
(__ \ "name").writes[String] and
(__ \ "account").writes[String] and
(__ \ "password").writes[String]
)(Credential)
Another fail: "value writes is not a member of play.api.libs.json.JsPath Note: implicit value credentialWrites is not applicable here because it comes after the application point and it lacks an explicit result type". Right, I understood the first part of an error, but not the second.
Finally I found a shorthand solution:
implicit val credentialWrites = Json.writes[Credential]
With this I've got no errors and the code finally worked. I've found the solution on this blog. It's said that the shorthand form is exactly the same as the one with "writes" above. But this "long" form didn't work for me.
Why is shorthand version working, while the long one isn't? Can somebody explain this?
Thank you!
PS Scala version: 2.10.2
The definitions you've given would work for Reads, but Writes needs a different kind of argument at the end. Take the following example:
case class Baz(foo: Int, bar: String)
val r = (__ \ 'foo).read[Int] and (__ \ 'bar).read[String]
val w = (__ \ 'foo).write[Int] and (__ \ 'bar).write[String]
r can be applied to a function (Int, String) => A to get a Reads[A], which means we can use it as follows (these are all equivalent):
val bazReader1 = r((foo: Int, bar: String) => Baz(foo, bar))
val bazReader2 = r(Baz.apply _)
val bazReader3 = r(Baz)
What we're doing is lifting the function into the applicative functor for Reads so that we can apply it to our Reads[Int] and Reads[String] (but you don't need to care about that if you don't want to).
w takes a different kind of argument (again, you don't need to care, but this is because Writes has a contravariant functor—it doesn't have an applicative functor):
val bazWriter1 = w((b: Baz) => (b.foo, b.bar))
We could write this equivalently as the following:
val bazWriter2 = w(unlift(Baz.unapply))
Here we're using the case class's automatically generated extractor, unapply, which returns an Option[(Int, String)]. We know in this case that it'll always return a Some, so we can use unlift (which comes from the functional syntax package, and just calls the standard library's Function.unlift) to turn the Baz => Option[(Int, String)] into the required Baz => (Int, String).
So just change your final line to )(unlift(Credential.unapply)) and you're good to go.