我只想从以下JSON中读取“value”
{
"field": "feed",
"value": {
"item": "post",
"verb": "add",
"post_id": 1234568567515,
"sender_id": 10200718414514
}
}
进入这个:
case class Value (
item: String,
verb: String,
itemId: Long,
senderId: Long
)
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 )
如何为Reads中的所有路径指定公共父节点“value”,而不是像(__ \“value”\“item”)那样重复它,(__ \“value”\“verb” )等等?
答案 0 :(得分:1)
此代码似乎有效:
implicit val valuereads = (__ \ "value").read {
((__ \ "item").read[String] and
(__ \ "verb").read[String] and
(__ \ "post_id").read[Long] and
(__ \ "sender_id").read[Long]
)(Value.apply _)
}
答案 1 :(得分:0)
不确定它是否是您要查找的内容,但如果您想跳过手动编写Reads
个对象,则可以使用宏。但是对于这种情况,你应该有父案例类,它将包含两个字段:field
和value
。
所以它会像:
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]
最后,您可以从value
对象中获取MyClass
。