mongodb - Akka HTTP Json Marshalling -


i'm building simple rest api using akka-http , mongodb persistence. marshalling , unmarshalling http requests i'm using spray json. following mongodb documentation defined entities that:

package entities  import org.mongodb.scala.bson.objectid  case class person(   _id: objectid,   firstname: string,   lastname: string,   email: string,   emailconfirmed: boolean,   telephone: string,   ... )  object person {    def apply(     firstname: string,     lastname: string,     email: string,     telephone: string,     ...   ): publisher = new publisher(     new objectid(),     firstname,     lastname,     email,     false,     telephone,     ...   ) } 

the problem approach have write lot of boilerplate code enable marshalling-unmarshalling:

implicit object publisheritemformat extends rootjsonformat[publisher] {   def write(publisher: publisher) = jsobject(     "_id" -> jsstring(publisher._id.tostring),     "firstname" -> jsstring(publisher.firstname),     "lastname" -> jsstring(publisher.lastname),     "email" -> jsstring(publisher.email),     "telephone" -> jsstring(publisher.telephone),     ...   )    def read(json: jsvalue) = {     val jsobject = json.asjsobject     jsobject.getfields(       "_id",       "firstname",       "lastname",       "email",       "telephone",       ...     ) match {       case seq(         _id,         firstname,         lastname,         email,         telephone,         ...       ) ⇒ publisher(         firstname.convertto[string],         lastname.convertto[string],         email.convertto[string],         telephone.convertto[string],         ...       )     }   } } 

i have approx 10 different entities have saved in mongo, , each of them have 5-15 fields. number of entities, kind of approach produce boilerplate.
better way of doing it, less boilerplate ? may-be there json-serialization library instead of "spray-json" can figure things out automatically less code ?
or how can define marshalling class org.mongodb.scala.bson.objectid using spray-json ? rid of boilerplate code.

use automatic derivation:

  object entitesjsonprotocol extends sprayjsonsupport defaultjsonprotocol {     implicit val placeresponseformat = jsonformat19(person.apply)     def persontojson(p: person) = p.tojson   } 

the persontojson method implemented don't have contaminate code json imports, note order of declaration important if person embedded inside publisher have declare personformat before publisherformat


Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -