【发布时间】:2019-03-07 21:08:11
【问题描述】:
我有一个看起来有点像这样的课程
import java.time.OffsetDateTime
import spray.json._
import DefaultJsonProtocol._
sealed trait Person {
def firstName: String
def country: String
def lastName: String
def salary: Option[BigDecimal]
}
case class InternalPerson(
firstName: String,
country: String,
lastName: Option[BigDecimal],
salary: Option[BigDecimal]
) extends Person
object Person {
def fromName(name: Name, country: String, salary: Option[BigDecimal]): Person = {
InternalPerson(
firstName = name.firstName,
lastName = name.lastName,
country = country,
salary = salary
)
}
}
object PersonJsonProtocol extends DefaultJsonProtocol {
implicit val personFormat = jsonFormat4(Person.apply)
}
我只是想为我的班级添加一个 json 支持。每当我从另一个类中导入协议和 spray.json._ 时,我都会得到:
Note: implicit value personFormat is not applicable here because it comes after the application point and it lacks an explicit result type
和
value apply is not a member of object of Person
关于如何让 Json 支持在 Scala 中扩展特征的伴生对象有什么想法吗?
【问题讨论】:
-
实际上 Person 不带 4 个参数对吧?人是一个对象。而且您还没有在您的 person 对象中定义您的 apply 方法。我建议编组/解组到类中,然后从那里,您可以使用对象应用将它们转换为相关格式。