scala play json未找到unapply或unapplySeq函数 [英] scala play json No unapply or unapplySeq function found

查看:46
本文介绍了scala play json未找到unapply或unapplySeq函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

播放文档中的此JSON自动映射示例失败.为什么? https://www.playframework.com/documentation/2.5.x/ScalaJsonAutomated

This JSON automated mapping example from the play documentation fails. why? https://www.playframework.com/documentation/2.5.x/ScalaJsonAutomated

libraryDependencies += "com.typesafe.play" %% "play" % "2.5.0"
---
import play.api.libs.json._
case class Resident(name: String, age: Int, role: Option[String])
implicit val residentWrites = Json.writes[Resident]
println(Json.toJson(Resident("john", 33, None)))
---
Error: No unapply or unapplySeq function found
      implicit val residentWrites = Json.writes[Resident]

推荐答案

有问题的代码或多或少是这样的:

The problematic code looked more or less like that:

import play.api.libs.json._

object Test {
  def main(args: Array[String]): Unit = {
    case class Resident(name: String, age: Int, role: Option[String])
    implicit val residentWrites = Json.writes[Resident]
    println(Json.toJson(Resident("john", 33, None)))
  }
}

这里的问题是,此宏显然不适用于在方法内部定义的类.这不是一个令人不安的限制,尽管我们宁愿不做这种事情.

The issue here was that this macro apparently doesn't work for classes defined inside methods. This is not a troubling limitation though as we rather don't do this sort of things.

要解决问题,可以将类定义def移到其他位置,例如对象级别

To resolve issue class def can be moved somewhere else, like object level

object Test {
  case class Resident(name: String, age: Int, role: Option[String])

  def main(args: Array[String]): Unit = {
    implicit val residentWrites = Json.writes[Resident]
    println(Json.toJson(Resident("john", 33, None)))
  }
}

或文件级别

case class Resident(name: String, age: Int, role: Option[String])

object Test {
  def main(args: Array[String]): Unit = {
    implicit val residentWrites = Json.writes[Resident]
    println(Json.toJson(Resident("john", 33, None)))
  }
}

我知道这只是出于测试目的,以查看最少的示例,但是我仍然会提到我们通常如何使用Writes定义类.

I understand that this was only for test purposes to see minimal example, but I will still mention how we usually define classes with Writes.

object Resident {
  implicit val residentWrites = Json.writes[Resident]
}

case class Resident(name: String, age: Int, role: Option[String])

这样,每当导入Resident时,其写操作都将位于隐式作用域中.

This way, whenever you import the Resident, its writes will be in the implicit scope.

这篇关于scala play json未找到unapply或unapplySeq函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆