Note that there are some explanatory texts on larger screens.

plurals
  1. POModifying JSON reads and writes in playframework 2.1
    primarykey
    data
    text
    <p>I'm a newbie and scala/play and need help with playframework's JSON reads/writes.</p> <p>I use Json.reads[T] and Json.writes[T] macros to define json reads and writes for my classes. However I'd like to have one property name to be (always) mapped differently. Namely, I have property named <code>id</code> in my classes and I want it to be represented as <code>_id</code> when object is converted to json and vice versa.</p> <p>Is there a way to modify reads/writes objects generated by Json.reads and Json.writes macros to achieve this or do I have to rewrite reads and writes manually just to have one property named differently?</p> <p><strong>EDIT</strong></p> <p>Let me try to explain the problem better. Consider the model object User:</p> <pre><code>case class User (id: BigInt, email: String, name: String) </code></pre> <p>When serializing User to json for purposes of serving json in context of a REST api the json should look like this:</p> <p>{ "id": 23432, "name": "Joe", "email: "joe@example.com" }</p> <p>When serializing User to json for purposes of storing/updating/reading form MongoDB json should look like:</p> <p>{ "_id": 23432, "name": "Joe", "email: "joe@example.com" }</p> <p>In other words everything is the same except when communicating with Mongo <code>id</code> should be represented as <code>_id</code>.</p> <p>I know I could manually write two sets of reads and writes for each model object (one to be used for web and another for communication with Mongo) as suggested by Darcy Qiu in the answer, however maintaining two sets of reads and writes that are nearly identical except for the id property seems like a lot of code duplication so I'm wondering if there is a better approach.</p>
    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.
    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