简体   繁体   English

Play Framework-具有案例类的Json.format案例类转换

[英]Play Framework - Json.format case class conversion with a case class

I'm not able to get the following to work, so don't know if it's even possible: 我无法执行以下操作,因此不知道是否有可能:

case class ItemA(name:String,itemB:ItemB)
case class ItemB(name:String)

object ToJson{
   implicit val itemAJson = Json.format[ItemA]
   implicit val itemBJson = Json.format[ItemB]
}

I get a compile error of something like: 我收到类似以下的编译错误:

No implicit format for ItemB available. 没有可用的ItemB隐式格式。 [error] implicit val itemAJson = Json.format[ItemA] [错误]隐式val itemAJson = Json.format [ItemA]

Pretty sure it can't be done, but is there a sensible approach to take? 可以肯定,这是不可能完成的,但是是否有明智的选择呢?

Play Framework 2.3 播放框架2.3

As your ItemA depends on ItemB so in order to create json.Format[ItemA] there must be defined json.Forma[ItemB] first, hence change the order first define itemBJson then itemAJson 由于您的ItemA依赖于ItemB,因此为了创建json.Format [ItemA],必须先定义json.Forma [ItemB],因此先更改顺序先定义itemBJson,然后再定义itemAJson

implicit val itemBJson = Json.format[ItemB]
implicit val itemAJson = Json.format[ItemA]

Another option is to lazy the implicit variables ... in this way it does not affect the order you write it. 另一种选择是延迟隐式变量...这样就不会影响您编写它的顺序。 I have many jsonFormat and they all work correctly like this: 我有很多jsonFormat,它们都可以像这样正常工作:

object ToJson {
   implicit lazy val itemAJson = Json.format[ItemA]
   implicit lazy val itemBJson = Json.format[ItemB]
}

Similar is the solution in the Play documentation . Play文档中的解决方案与此类似。 for recursive types. 用于递归类型。

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

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