简体   繁体   中英

Play Framework Json Object mapping partial objects

Another Play Framework 2.1 question as the documentation is too techie for me to wrap my head around.

If I have a scala case class object that represents something, say a server:

case class Server(name: String, ip: String, operatingsystem: enums.OperatingSystem)

implicit val serverreads = ((__ \ "name").read[String] and (__ \ "ip").read[String] and (__ \ "os").read[enums.OperatingSystem])(Server.apply _)

implicit val serverwrite = ((__ \ "name").write[String] and (__ \ "ip").write[String] and (__ \ "os").write[enums.OperatingSystem])(unlift(Server.unapply))

I create my Json reads and writes for it and I can process the whole object, this is fine.

But is it possible to map partial objects?

For example, if I had a server that wasn't active it may not have an IP, now I know I could change it to an Option[String] and map None, so this isn't a perfect example, but if I wanted to simplify my Json model without changing the underlying case class, can I map some values to my class fields, whilst leaving the others at the default?

Thanks

Tom

You could simply create a custom apply methond ie simplaApply . Also you could create a object SimpleServer matching your json structure. When working with case classes you can define an instance with default data and copy the instance while overwriting with new data ie i.copy(prop1=42) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM