Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In my humble opinion, your approach is not ideal and you have to rethink about your design. Let me explain you why.</p> <p>While you could effectively develop a <code>Format[A]</code> which is able to read both formats, you are not able to write a <code>Format[A]</code> which can write the two formats</p> <pre><code>trait Format[T]{ def reads (json: JsValue): T def writes (o: T): JsValue } </code></pre> <p>As you see, the writes method has a single parameter, so your <code>Format[Test]</code> won't be able to know if it should use one or the other output format. If you followed the reasoning you would agree that the <code>Format</code> trait is delegated to write and read from/to a <strong>specific</strong> Json Format, not to choose between formats. Your logic to choose the right format has nothing to do with reading and writing the right format, and you should decouple it. </p> <p>Saying that, you can re-use your Format[Test] in the following way:</p> <pre><code>case class ObjectParser(nestedFormatter:Format[T]) extends Format[T]{ def reads (json: JsValue): T = nestedFormatter.read(json \ "object") def writes (o: T): JsValue = JsObject("object" -&gt; nestedFormatter.write(o)) } </code></pre> <p>This class would take any existing formatter and make it able to read and write inside an additional "object" node. </p> <p>Imagine now you have a controller which needs to generate or parse two different answers according to the url endpoints:</p> <pre><code>object TestController extends Controller { def endPoint1Action = Action{ implicit request =&gt; generateResponse(FopReads) } def endPoin21Action = Action{ implicit request =&gt; generateResponse(ObjectParser(FopReads)) } def generateResponse(formatter:Format[Test])(implicit request:Request[AnyContent]):Response = BadRequest("!") } </code></pre>
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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