简体   繁体   English

Play Framework 2.2.x Scala JSON读取中的公共路径前缀

[英]Common path prefix in Play framework 2.2.x scala JSON Reads

I would like to only read "value" from the following JSON 我只想从以下JSON读取“值”

{
  "field": "feed",
  "value": {
    "item": "post",
    "verb": "add",
    "post_id": 1234568567515,
    "sender_id": 10200718414514
  }
}

into this: 到这个:

case class Value (
  item: String,
  verb: String,
  itemId: Long,
  senderId: Long
)

The Reads[Value] looks like this: Reads [Value]看起来像这样:

implicit val valueReads: Reads[Value] = (
  (__ \ "item").read[String] and
  (__ \ "verb").read[String] and
  (__ \ "post_id").read[Long] and
  (__ \ "sender_id").read[Long]
) ( Value )

How can I specify the common parent node "value" for all the paths in Reads without repeating it all over the place like (__ \\ "value" \\ "item"), (__ \\ "value" \\ "verb") etc.? 我如何为Reads中的所有路径指定公共父节点“值”,而不在(__ \\“ value” \\“ item”),(__ \\“ value” \\“ verb”)等各处重复它。 ?

This code seems to work: 这段代码似乎有效:

implicit val valuereads = (__ \ "value").read {
  ((__ \ "item").read[String] and
   (__ \ "verb").read[String] and
   (__ \ "post_id").read[Long] and
   (__ \ "sender_id").read[Long] 
   )(Value.apply _)  
}

Not sure if it is what you are looking for, but if you want skip manually writing Reads objects, you can use macros. 不确定是否要查找它,但是如果要跳过手动编写Reads对象的操作,则可以使用宏。 But for that case you should have parent case class, which will have inside two fields: field and value . 但是对于这种情况,您应该具有父案例类,该类将在两个字段内: fieldvalue

So it'll be something like: 因此,它将类似于:

case class Value (
  item: String,
  verb: String,
  itemId: Long,
  senderId: Long
)

case class MyClass(field: String, value: Value)


implicit val myClassReads = Json.reads[MyClass]
implicit val valueReads = Json.reads[Value]

So at the end you can get your value from the MyClass object. 因此,最后您可以从MyClass对象获取您的value

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

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