Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing Reads, Writes and Formats in Play framework
    primarykey
    data
    text
    <p>I have some models in a Play! application that I would like to serialize/deserialize to and from JSON. I used to have separate methods for that, but I have seen that the preferred way is to give an implicit instance of <code>Formats[T]</code> or <code>Reads[T]</code>, like</p> <pre><code>import play.api.libs.json.{ JsValue, Reads } case class Foo(bar: Int, ...) object Foo { implicit object FooReads extends Reads[Foo] { def reads(json: JsValue): Foo = //whatever } } </code></pre> <p>Now, it may happen that the model has the correct fields in the JSON, but it does not validate. In this case, I am not able to deserialize - I should get an exception when using <code>json.as[Foo]</code> or <code>None</code> when using <code>json.asOpt[Foo]</code>.</p> <p>If I throw an exception when I find a field that does not validate, everything seems to work as expected. But I took the care of trying to find out what exception I should throw, and in the source for <code>JsValue</code> I found this</p> <pre><code>def asOpt[T](implicit fjs: Reads[T]): Option[T] = fjs.reads(this).fold( valid = v =&gt; Some(v), invalid = _ =&gt; None ).filter { case JsUndefined(_) =&gt; false case _ =&gt; true } </code></pre> <p>Now, I cannot understand how this is supposed to work. The implicit instance of <code>fjs</code> is supplied by myself in the companion object, so I know that <code>fjs.reads(this)</code> either returns a <code>Foo</code> or throws an exception.</p> <p>Where is this <code>fold</code> coming from? It certainly is not a method on <code>Foo</code>. I guess one could have an implicit conversion, but it should be from <code>Any</code> to something with a <code>fold</code> method, so it could not be of much interest. Even worse, if <code>fjs.reads(this)</code> throws an exception, there is nothing to catch it!</p> <blockquote> <p>So, how should one handle invalid input in the JSON in an instance of <code>Reads[T]</code>? And how does the mechanism above actually work?</p> </blockquote>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload