代码之家  ›  专栏  ›  技术社区  ›  Niro

对伴生对象的JSON支持

  •  0
  • Niro  · 技术社区  · 6 年前

    我有一节课看起来有点像那样

    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)
    }
    

    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中扩展trait的伴随对象吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Ben Weaver    6 年前

    如果您使用case类InternalPerson定义了隐式json格式,那么应该启用: implicit val personFormat = jsonFormat4(InternalPerson)

        2
  •  1
  •   Patryk Rudnicki    6 年前

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

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

    对于基本类型来说,使用它就足够了 Json.format[ClassName] . 如果你有更复杂的东西,你可以自己写 writes reads . 我知道这个问题是关于喷雾的,但另一个解决办法可能是好的。

    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