【问题标题】:JSON support for companion object伴随对象的 JSON 支持
【发布时间】: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 方法。我建议编组/解组到类中,然后从那里,您可以使用对象应用将它们转换为相关格式。

标签: json scala spray


【解决方案1】:

如果您根据案例类、InternalPerson 定义了隐式,则应启用 json 格式:implicit val personFormat = jsonFormat4(InternalPerson)

而且您不必定义 apply() 方法,您必须在 Person trait 或其任何实现中执行该方法。

【讨论】:

  • Re Shankar 上面的评论,是的,弄清楚 Person 和 InternalPerson 应该接受多少参数。如果只有 3 个参数,那么我建议的隐式应该是: ...jsonFormat3(InternalPerson)
【解决方案2】:

你可以使用play框架来处理Json。

https://www.playframework.com/documentation/2.6.x/ScalaJson

我认为它非常简单直观。

对于原始类型,使用Json.format[ClassName] 就足够了。如果您有更复杂的内容,您可以编写自己的writesreads。我知道这个问题是关于喷雾的,但另一种解决方案可能会很好。

例如,对于InternalPerson,它将是:

import play.api.libs.json.Json

case class InternalPerson {
  firstName: String,
  country: String,
  lastName: Option[BigDecimal],
  salary: Option[BigDecimal]
)

object InternalPerson {
  implicit val format = Json.format[InternalPerson]
}

如果您想使用Trait 进行操作,则相同。有时您需要显式地编写读写操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多