Slick result to json - json

What I would like to do is inspired by this: https://www.playframework.com/documentation/2.5.x/ScalaJsonHttp
I would like to have Person that can have Address attached to them. It's many to many actually in my example, so a person can have multiple addresses and an address may be attached to multiple persons.
The query was not a problem. I get back: Future[Seq[((Person, PersonAddress), Address)]] from the DB layer.
My problem begins when I want to return the result as json. For a Person alone it would be simple, as the case class would already take care, but for such a Seq it's more complicated.
So I tried this:
1) DB just returns Future[Seq[((Person, PersonAddress)]] for now, to make things easier for me to understand
2) case class PersonWithPersonAddress(person: Person, personAddress: PersonAddress) was added to be a helper instead of using Tuple2[Person, PersonAddress]
3) I wrote the following writer:
implicit val writes: Writes[PersonWithPersonAddress] = (
(JsPath \ "person").write[Person],
(JsPath \ "personAddress").write[PersonAddress]
) (unlift(PersonWithPersonAddress.unapply))
According to the compiler this is not enough.
No Json serializer found for type PersonAddress. Try to implement an implicit Writes or Format for this type.
Then I tried to add:
implicit val personFormat = Json.format[Person]
implicit val PersonAddressFormat = Json.format[PersonAddress]
but I got
(play.api.libs.json.OWrites[Person], play.api.libs.json.OWrites[PersonAddress]) does not take parameters
I proceeded to manually write my Writes[Person] but this does not change a thing to Json.format[Person] of course.
Now I am out of ideas

This should be enough for you:
import play.api.libs.json.Json
implicit val personFormat = Json.format[Person]
implicit val personAddressFormat = Json.format[PersonAddress]
implicit val personWithPersonAddressFormat = Json.format[PersonWithPersonAddress]
If you'd still want to define Writes field-by-field, you should try this:
import play.api.libs.functional.syntax._
import play.api.libs.json._
implicit val personWrites = Json.writes[Person]
implicit val personAddressWrites = Json.writes[PersonAddress]
implicit val personWithAddressWrites: Writes[PersonWithPersonAddress] = (
(__ \ "person").write[Person] and
(__ \ "personAddress").write[PersonAddress]
)(unlift(PersonWithPersonAddress.unapply))

Related

Parsing an object-sequence with Play-JSON library

As a disclaimer: I'm very new to Scala and functional programming in general.
I have the following classes:
case class A(
field1: String,
field2: DateTime
)
case class B(
listOfStuff: Seq[A]
)
object A{
def create(field1: String, field2: DateTime): A = A(field1, field2)
}
object B{
def create(listOfStuff: Seq[A]): B = B(listOfStuff)
}
(The create() functions exist because I sometimes had issues in my code when using apply(). Let's ignore this, I doubt it's relevant.)
I get these objects in JSON format and I try to parse them using the Play-JSON library. An important aspect is that the list (Seq) can be missing from the JSON text, it's an optional field.
With that in mind, this is how I wrote that particular line:
private implicit val messageReader = (
//...
(__ \ "stuff").readNullable[Seq[A]].map(_.getOrElse(Seq()))
//...
)(B.create _)
When compiling, I get the following error:
Error:(!line!, !column!) No Json deserializer found for type Seq[A].
Try to implement an implicit Reads or Format for this type.
From what I saw in this question, apparently you need to have an implicit instance of Reads[T] for every type T that is not part of the language (or something like that, did I mention I'm new to this?)
So I also added a secondary Reads[T] in the same scope, my code now looked like this:
private implicit val messageReader = (
(__ \ "stuff").readNullable[Seq[A]].map(_.getOrElse(Seq()))
)(B.create _)
private implicit val anotherReader = (
(__ \ "field1").read[String] and
(__ \ "field2").read[String].map(org.joda.time.DateTime.parse)
)(A.create _)
However I still get that same error on the same line.
I feel like there's some very easy and obvious problem here, but I can't figure out what it is.
How do I fix this?
if B.create accepts a single argument then its reads can look like this:
private implicit val messageReader : Reads[B] =
(__ \ "stuff").readNullable[Seq[A]].map(_.getOrElse(Seq())).map(B.create)

Serialize set to json with a custom Writes in Scala Play 2.4

I have a use case where I want to serialize a User entity to json. This user entity includes private fields I don't want to expose, such as password.
I'm using a custom OWrites to deal with this when I return a single user:
val userSafeWrites: OWrites[User] = (
(__ \ EMAIL_FIELD).write[String] ~
(__ \ FIRST_NAME_FIELD).write[String] ~
(__ \ LAST_NAME_FIELD).write[String] ~
(__ \ PHONE_NUMBER_FIELD).write[Option[String]] ~
(__ \ ID_FIELD).write[Long]
)(p => (p.email, p.firstName, p.lastName, p.phoneNumber, p._id.get))
and then I specify the OWrites instead of using the implicit:
Ok(Json.toJson(user)(User.userSafeWrites))
However, I have now to return a Set[User].
How can I do that? Do I need to implement a OWrites[Set[User]]? I can understand how to do that if I was to return an object with a field name with the results, such as:
{
"users": [{user1}, {user2}]
}
However, I want to return simply an array, to comform to the output in other endpoints:
[{user1}, {user2}]
Or I should map each element of the set to a JsObject and apply the custom OWrites to each object? What would be the most efficient way to do that?
I feel this is something pretty simple and I'm just being a moron for not finding the answer myself.
You are reimplementing writes for traversable that are trivial anyway but still. Another option is to reuse that Writes
val users: Set[User] = ???
Json.toJson(users)(Writes.traversableWrites(userSafeWrites))
Writes for Traversable are defined as follows:
implicit def traversableWrites[A: Writes] = Writes[Traversable[A]] { as =>
JsArray(as.map(toJson(_)).toSeq)
}
Which is just what you did.
It takes as implicit parameter of type Writes[A] and uses it to write each member. You can pass this parameter explicitly to obtain desired Writes.
Another option as #cchantep mentioned is just to import your implicit where you need it.
For example, having some model with default writes
case class User(num: Int)
object User {
implicit val writes = Json.writes[User]
}
and another object with the custom writes
object OtherWrites {
implicit val custom: Writes[User] = new Writes[User] {
override def writes(o: User): JsValue = JsNull
}
}
in the class that is the client
object Client extends App {
val obj = List(User(1))
print(Json.toJson(obj))
}
You would get [{"num":1}] printed as default writes are present in the implicit scope because they are defined in companion object of User.
You can import custom writes where you need them and those from companion object will be overriden
object Client extends App {
import test.OtherWrites._
val obj = List(User(1))
print(Json.toJson(obj))
}
And you get [null] printed.
Meh, it's as simple as:
Ok(JsArray(userSet.map(user => Json.toJson(user)(User.userSafeWrites)).toSeq))
Spent over one hour googling and trying to sort it out in the most ridiculous ways before posting the question.
Solved it in one minute after posting the question.
Having one of those days...
unless there's a better way to do it

Making Reads and Writes in Scala Play for lists of custom classes

So I have two classes in my project
case class Item(id: Int, name: String)
and
case class Order(id: Int, items: List[Item])
I'm trying to make reads and writes properties for Order but I get a compiler error saying:
"No unapply or unapplySeq function found"
In my controller I have the following:
implicit val itemReads = Json.reads[Item]
implicit val itemWrites = Json.writes[Item]
implicit val listItemReads = Json.reads[List[Item]]
implicit val listItemWrites = Json.writes[List[Item]]
The code works for itemReads and itemWrites but not for the bottom two. Can anyone tell me where I'm going wrong, I'm new to Play framework.
Thank you for your time.
The "No unapply or unapplySeq function found" error is caused by these two:
implicit val listItemReads = Json.reads[List[Item]]
implicit val listItemWrites = Json.writes[List[Item]]
Just throw them away. As Ende said, Play knows how to deal with lists.
But you need Reads and Writes for Order too! And since you do both reading and writing, it's simplest to define a Format, a mix of the Reads and Writes traits. This should work:
case class Item(id: Int, name: String)
object Item {
implicit val format = Json.format[Item]
}
case class Order(id: Int, items: List[Item])
object Order {
implicit val format = Json.format[Order]
}
Above, the ordering is significant; Item and the companion object must come before Order.
So, once you have all the implicit converters needed, the key is to make them properly visible in the controllers. The above is one solution, but there are other ways, as I learned after trying to do something similar.
You don't actually need to define those two implicits, play already knows how to deal with a list:
scala> import play.api.libs.json._
import play.api.libs.json._
scala> case class Item(id: Int, name: String)
defined class Item
scala> case class Order(id: Int, items: List[Item])
defined class Order
scala> implicit val itemReads = Json.reads[Item]
itemReads: play.api.libs.json.Reads[Item] = play.api.libs.json.Reads$$anon$8#478fdbc9
scala> implicit val itemWrites = Json.writes[Item]
itemWrites: play.api.libs.json.OWrites[Item] = play.api.libs.json.OWrites$$anon$2#26de09b8
scala> Json.toJson(List(Item(1, ""), Item(2, "")))
res0: play.api.libs.json.JsValue = [{"id":1,"name":""},{"id":2,"name":""}]
scala> Json.toJson(Order(10, List(Item(1, ""), Item(2, ""))))
res1: play.api.libs.json.JsValue = {"id":10,"items":[{"id":1,"name":""},{"id":2,"name":""}]}
The error you see probably happens because play uses the unapply method to construct the macro expansion for your read/write and List is an abstract class, play-json needs concrete type to make the macro work.
This works:
case class Item(id: Int, name: String)
case class Order(id: Int, items: List[Item])
implicit val itemFormat = Json.format[Item]
implicit val orderFormat: Format[Order] = (
(JsPath \ "id").format[Int] and
(JsPath \ "items").format[JsArray].inmap(
(v: JsArray) => v.value.map(v => v.as[Item]).toList,
(l: List[Item]) => JsArray(l.map(item => Json.toJson(item)))
)
)(Order.apply, unlift(Order.unapply))
This also allows you to customize the naming for your JSON object. Below is an example of the serialization in action.
Json.toJson(Order(1, List(Item(2, "Item 2"))))
res0: play.api.libs.json.JsValue = {"id":1,"items":[{"id":2,"name":"Item 2"}]}
Json.parse(
"""
|{"id":1,"items":[{"id":2,"name":"Item 2"}]}
""".stripMargin).as[Order]
res1: Order = Order(1,List(Item(2,Item 2)))
I'd also recommend using format instead of read and write if you are doing symmetrical serialization / deserialization.

Converting JSON in one format to another in Scala

I'm looking for suggestions or libraries that can help me convert JSON (with nested structure) from one format to another in Scala.
I saw there are a few JavaScript and Java based solutions. Anything in Scala ?
I really like the Play JSON library. It's API is very clean and it's very fast even if some parts have a slightly steeper learning curve. You can also use the Play JSON library even if you aren't using the rest of Play.
https://playframework.com/documentation/2.3.x/ScalaJson
To convert JSON to scala objects (and vice versa), Play uses implicits. There is a Reads type which specifies how to convert JSON to a scala type, and a Writes type which specifies how to convert a scala object to JSON.
For example:
case class Foo(a: Int, b: String)
There are a few different routes you can take to convert Foo to JSON. If your object is simple (like Foo), Play JSON can create a conversion function for you:
implicit val fooReads = Json.reads[Foo]
or you can create a custom conversion function if you want more control or if your type is more complex. The below examples uses the name id for the property a in Foo:
implicit val fooReads = (
(__ \ "id").read[Int] ~
(__ \ "name").read[String]
)(Foo)
The Writes type has similar capabilities:
implicit val fooWrites = Json.writes[Foo]
or
implicit val fooWrites = (
(JsPath \ "id").write[Int] and
(JsPath \ "name").write[String]
)(unlift(Foo.unapply))
You can read more about Reads/Writes (and all the imports you will need) here: https://playframework.com/documentation/2.3.x/ScalaJsonCombinators
You can also transform your JSON without mapping JSON to/from scala types. This is fast and often requires less boilerplate. A simple example:
import play.api.libs.json._
// Only take a single branch from the input json
// This transformer takes the entire JSON subtree pointed to by
// key bar (no matter what it is)
val pickFoo = (__ \ 'foo).json.pickBranch
// Parse JSON from a string and apply the transformer
val input = """{"foo": {"id": 10, "name": "x"}, "foobar": 100}"""
val baz: JsValue = Json.parse(input)
val foo: JsValue = baz.transform(pickFoo)
You can read more about transforming JSON directly here: https://playframework.com/documentation/2.3.x/ScalaJsonTransformers
You can use Json4s Jackson. With PlayJson, you have to write Implicit conversions for all the case classes. If the no. of classes are small, and will not have frequent changes while development, PlayJson seems to be okay. But, if the case classes are more, I recommend using json4s.
You need to add implicit conversion for different types, so that json4s will understand while converting to json.
You can add the below dependency to your project to get json4s-jackson
"org.json4s" %% "json4s-jackson" % "3.2.11"
A sample code is given below (with both serialization and deserialization):
import java.util.Date
import java.text.SimpleDateFormat
import org.json4s.DefaultFormats
import org.json4s.jackson.JsonMethods._
import org.json4s.jackson.{Serialization}
/**
* Created by krishna on 19/5/15.
*/
case class Parent(id:Long, name:String, children:List[Child])
case class Child(id:Long, name:String, simple: Simple)
case class Simple(id:Long, name:String, date:Date)
object MainClass extends App {
implicit val formats = (new DefaultFormats {
override def dateFormatter = new SimpleDateFormat("yyyy-MM-dd")
}.preservingEmptyValues)
val d = new Date()
val simple = Simple(1L, "Simple", d)
val child1 = Child(1L, "Child1", simple)
val child2 = Child(2L, "Child2", simple)
val parent = Parent(1L, "Parent", List(child1, child2))
//Conversion from Case Class to Json
val json = Serialization.write(parent)
println(json)
//Conversion from Json to Case Class
val parentFromJson = parse(json).extract[Parent]
println(parentFromJson)
}

Play json parse missing field as empty array

Using play-json 2.3
How do i parse this
{i: 0}
into this
case class A(i: Int, s: Seq[Int])
i would very much like to reuse Json.format macro
at the moment it gives me "missing path s"
UPD:
i ended up writing a custom format and pimping it onto JsPath:
implicit class JsPathExtensions(path: JsPath) {
//return mzero if the path is missing
def lazyFormatNullableM[T: Monoid](f: => Format[T]): OFormat[T] = OFormat(path.lazyReadNullable(f).map(_.orZero), new OWrites[T] {
override def writes(o: T) = path.lazyWriteNullable(f).writes(o.some)
})
}
If the path is missing, I don't see any way to utilize the macro without changing the class. In which case, you can define Reads using json combinators and use the macro for Writes.
import play.api.libs.json._
import play.api.libs.functional.syntax._
implicit val reads: Reads[A] = (
(__ \ "i").read[Int] and
(__ \ "s").read[Seq[Int]].orElse(Reads.pure(Nil))
)(A.apply _)
implicit val writes: Writes[A] = Json.writes[A]
The json macros only cover a very limited range of use cases, and it's inevitable that you'll run into a case where you must write your own Reads or Writes.
The easiest way to utilise the Json.format[A] macro would be to slightly alter your definition of A:
case class A(i: Int, s: Option[Seq[Int]])
The usage of an Option here is pretty clear and you can map over it and do lots of good things, but if you really want to treat s like it's an empty collection, you could enhance your case class a little more:
case class Foo(i: Int, s: Option[Seq[Int]]) {
lazy val theSeq:Seq[Int] = s.getOrElse(Seq[Int]())
}
Now if you access theSeq, there is absolutely no difference between incoming JSON that omitted s and JSON that supplied an empty array for s.