简体   繁体   English

如何使用Scala组合器读取case类中的可选json值

[英]How to read optional json values in case class using scala combinators

I am trying to process JSON which can optionally have 'info' and its contains. 我正在尝试处理JSON,JSON可以选择包含“信息”及其包含的内容。 Which is captured in the following case class and the combinator to read the JSON in object. 在以下案例类和组合器中捕获了这些内容,以读取对象中的JSON。 But the code fails to compile. 但是代码无法编译。 Is there better way of handling this? 有更好的方法来处理此问题吗? Info can be empty. 信息可以为空。

case class Info(sometimestamp: Option[Long])

object Info {
  implicit val InfoReads: Reads[Info] = (
    (JsPath \ "sometimestamp").readNullable[Long]
  )(Info.apply _)
}

{
  ...
  "info" : {
    "sometimestamp" : 1414535323436
  }
}

Compilation error: 编译错误:

found   : play.api.libs.json.Reads[Option[Long]]
[error]  required: play.api.libs.json.Reads[models.Payload.Info]
[error]   ) (Info.apply _)

scala version: 2.11.2 Scala版本:2.11.2

thanks, 谢谢,

I don't think the functional syntax for combinators work when you're not actually combining anything. 当您实际上没有进行任何组合时,我认为组合器的功能语法不起作用。 This does, however: 但是,这样做:

implicit val InfoReads: Reads[Info] = 
    (JsPath \ "sometimestamp").readNullable[Long].map(Info(_))

You might also consider just using the JSON inception macro for such a simple case class: 您可能还考虑将JSON inception宏用于这种简单的案例类:

implicit val InfoReads: Reads[Info] = Json.reads[Info]

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

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