scala.MatchError:转换为JSON时为null

时间:2015-03-11 23:48:03

标签: json scala playframework-2.0

我有一个基于Play的应用程序!框架。有下一个课程

package models

sealed trait Role

object Role {

  case object Administrator extends Role
  case object Accountant extends Role
  case object Cashier extends Role
  case object Repairman extends Role

  implicit def Role2Int(role: Role): Int = {
    role match {
      case Administrator => 1
      case Accountant => 2
      case Cashier => 4
      case Repairman => 8
      case _ => throw new NotImplementedError(s"Conversion from $role to Int is not supported yet.")
    }
  }

  implicit def Int2Role(i: Int): Role = {
    i match {
      case 1 => Administrator
      case 2 => Accountant
      case 4 => Cashier
      case 8 => Repairman
      case _ => throw new NotImplementedError(s"Not supported role value.")
    }
  }
}

case class User(
  id: Long,
  lastName: String,
  firstName: String,
  middleName: Option[String],
  role: Role,
  creationDate: Date,
  editDate: Option[Date],
  creatorId: Long,
  editorId: Option[Long]
)

我需要的是将用户类型的实例序列化为JSON。要使用标准游戏的json-serializer,我必须实现一个作家。

  Btw:奇怪的是,必须编写如此多的代码才能获得   这种简单情况的结果(读者也一样)。可能在那里   是更好的解决方案吗?

好的,作家已经完成了。但是当我尝试序列化时

import java.sql.Date

import models.Role.Accountant
import models._
import play.api.libs.json.{Writes, Json}

implicit val userWrites = new Writes[User] {
  def writes(user: User) = Json.obj(
    "id" -> user.id,
    "lastName" -> user.lastName,
    "firstName" -> user.firstName,
    "middleName" -> user.middleName,
    "role" -> Role.Role2Int(user.role),
    "creationDate" -> user.creationDate,
    "editDate" -> user.editDate,
    "creatorId" -> user.creatorId,
    "editorId" -> user.editorId
  )
}

val user = User(1, "Smith", "John", null, Accountant, new Date(System.nanoTime()), null, 0, null)

Json.toJson(user)

我得到了

scala.MatchError: null
    at play.api.libs.json.DefaultWrites$$anon$7.writes(app.sc2.tmp:180)
    at play.api.libs.json.DefaultWrites$$anon$7.writes(app.sc2.tmp:178)
    at play.api.libs.json.Json$.toJsFieldJsValueWrapper(app.sc2.tmp:139)
    at #worksheet#.$anon$1.writes(app.sc2.tmp:12)
    at #worksheet#.$anon$1.writes(app.sc2.tmp:7)
    at play.api.libs.json.Json$.toJson(app.sc2.tmp:104)
    at #worksheet#.get$$instance$$res1(app.sc2.tmp:25)
    at #worksheet#.#worksheet#(app.sc2.tmp:49)

我做错了什么?

1 个答案:

答案 0 :(得分:2)

该行:

val user = User(1, "Smith", "John", null, Accountant, new Date(System.nanoTime()), null, 0, null)

应该是:

val user = User(1, "Smith", "John", None, Accountant, new Date(System.nanoTime()), None, 0, None)

如上面的评论中所述,将null更改为None。