Reputation: 4811
I'm just comparing how you would both serialize and deserialize an object to and from JSON in java.
ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'john smith'}";
User user = mapper.readValue(jsonInString, User.class);
With the Playframework and Scala, I have to create these reads and writes mappers and they are very verbose. (see: https://www.playframework.com/documentation/2.5.x/ScalaJsonHttp)
Why can't it just "work" like it does with java w/Jackson?
I have my models, and I want to simply read/write then to JSON. With Java, I don't have any boilerplate code to write.
Upvotes: 1
Views: 138
Reputation: 13859
from https://www.playframework.com/documentation/2.5.x/ScalaJsonInception
We have had a few complaints from some people who think it’s not cool to write a Reads[TheirClass] because usually Java JSON frameworks like Jackson or Gson do it behind the curtain without writing anything. We argued that Play2.1 JSON serializers/deserializers are:
- completely typesafe,
- fully compiled,
- nothing was performed using introspection/reflection at runtime.
The ObjectMapper
in Jackson is none of these things. It relies heavily on reflection, so if you feed your class files through an obfuscator it might completely break. Even if you don't, there is no guarantee at compile time that the class you are trying to deserialize is actually deserializable.
Part of the draw of Scala is that it provides very strong compile-time guarantees. Implicits (e.g. typeclasses like Reads
and Writes
) factor into that, though they do come with some boilerplate/overhead.
The Play devs hear your complaint, but it's very unlikely that the Reads
and Writes
will go away. Instead, they're trying to make it a bit less verbose by providing a macro that finds code like this:
implicit val personReads = Json.reads[Person]
and interprets it like this, based on the Person
constructor:
implicit val personReads = (
(__ \ 'name).read[String] and
(__ \ 'age).read[Int] and
(__ \ 'lovesChocolate).read[Boolean]
)(Person)
Upvotes: 8