简体   繁体   English

播放框架Json Object映射部分对象

[英]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. Play框架2.1的另一个问题是,文档对我来说太过技巧了,我不敢动摇。

If I have a scala case class object that represents something, say a server: 如果我有一个表示某种东西的scala case类对象,请说一台服务器:

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. 我创建Json对其进行读写,并且可以处理整个对象,这很好。

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? 例如,如果我有一个不活动的服务器,则它可能没有IP,现在我知道可以将其更改为Option [String]并映射None,所以这不是一个完美的例子,但是如果我想为了简化我的Json模型而不更改基础案例类,我可以将一些值映射到我的类字段,而将其他值保留为默认值吗?

Thanks 谢谢

Tom 汤姆

You could simply create a custom apply methond ie simplaApply . 您可以简单地创建一个自定义应用方法,即simplaApply Also you could create a object SimpleServer matching your json structure. 您也可以创建与您的json结构匹配的对象SimpleServer 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) . 使用案例类时,您可以使用默认数据定义一个实例,并在用新数据覆盖时复制该实例,即i.copy(prop1=42)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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